【发布时间】:2018-07-19 15:13:31
【问题描述】:
我目前正在开发一个使用 Visual Studio 中的 Serenity 模板 (Serene) 的基本 CRUD Web 应用程序。此模板提供对多个插件的访问。 Sergen 插件生成为指定数据库创建 CRUD 表的 c# 和 html 文件。 jQuery 验证插件用于修改客户端字段验证。我正在尝试通过将以下 jQuery 和正则表达式(注释部分)组合添加到 TableIndex.cshtml 文件(由 Sergen 生成)中来向频率输入字段添加自定义字段验证:
{
ViewData["Title"] = Serenity.LocalText.Get("Db.Default.Table.EntityPlural");
}
<div id="GridDiv"></div>
<script type="text/javascript">
jQuery(function () {
new SerenityNowSolution.Default.TableGrid($('#GridDiv'), {}).init();
Q.initFullHeightGridPage($('#GridDiv'));
});
//The following is code that I added:
$(document).ready(function () {
$.validator.addMethod("TableDialog1_Frequency", function (value, element) {
return this.optional(element) || /(\d)+(d|h|m|s)/.test(value);
}, "Frequency is invalid: Please enter a valid frequency.");
$("#TableDialog1_Form").validate({
rules: {
TableDialog1_Frequency: "required TableDialog1_Frequency",
},
});
});
</script>
据我所知,这是 Sergen 生成的唯一 cshtml 文件。我添加自定义字段验证的尝试遇到了一些问题:
我不确定我添加的代码的位置(如果这是要编辑的正确文件)。
我添加的代码目前尝试通过向 validate 插件中的验证器函数添加正则表达式规则(方法)来向频率输入字段添加验证。不幸的是,Sergen 生成的代码“自动创建”(由于缺乏更好的描述)包含频率输入字段(id = TableDialog#_Frequency)的添加行模式(id = TableDialog#_Form)。在我上面的代码中,我尝试将字段验证添加到特定模式的输入字段(表单/频率#1)。但是,每次在网页上单击添加行按钮时,出现的模式都会在其 id 中具有唯一的标识号。看来我需要编辑模态生成代码以删除这些数字,或者修改我的验证代码来解决这个问题。我也不确定该怎么做。
以下代码用于生成添加行模式(TableDialog#_Form):
namespace SerenityNowSolution.Default {
@Serenity.Decorators.registerClass()
export class TableDialog extends Serenity.EntityDialog<TableRow, any> {
protected getFormKey() { return TableForm.formKey; }
protected getIdProperty() { return TableRow.idProperty; }
protected getLocalTextPrefix() { return TableRow.localTextPrefix; }
protected getNameProperty() { return TableRow.nameProperty; }
protected getService() { return TableService.baseUrl; }
protected form = new TableForm(this.idPrefix);
}
}
感谢您抽出宝贵时间阅读本文。如果我应该显示任何其他代码,请告诉我。任何帮助将不胜感激。
更新:
这是我目前添加的代码(在进行了建议的更改之后):
$(document).ready(function () {
$.validator.addMethod(
"regex",
function (value, element, regexp) {
var re = new RegExp(regexp);
return this.optional(element) || re.test(value);
},
"Please check your input."
);
});
$(document).on('click', '.tool-button.save-and-close-button', function () {
var item = $("div.field.Frequency input").attr("id");
var abc = $("div.s-Form form").attr("id");
$(abc).validate();
$(item).rules("add", {
regex: "^(\d)+(d|h|m|s)$"
});
$(abc).validate();
});
$(document).on('click', '.tool-button.apply-changes-button.no-text', function () {
var item = $("div.field.Frequency input").attr("id");
var abc = $("div.s-Form form").attr("id");
$(abc).validate();
$(item).rules("add", {
regex: "^(\d)+(d|h|m|s)$"
});
$(abc).validate();
});
很遗憾,字段验证仍未进行。
【问题讨论】:
-
您是否将 Unobtrusive Validation 插件用作 ASP 的一部分?如果是这样,那么您不能构造对
.validate()的调用,因为它将被忽略,而支持由 Unobtrusive Validation 插件自动构造的调用。这就是使用非侵入式验证的全部意义所在。 -
不,我没有使用那个插件。我也不能(或者至少不知道如何/在我的解决方案中找不到它)访问模态表单组件的 html 代码,这会阻止我添加数据属性。
标签: jquery asp.net jquery-validate