向ASP中动态创建的元素添加jQuery验证程序规则
我在MVC3项目的页面上动态插入了一些表单字段。通常我们会在服务器端添加jQuery验证,但在这种情况下我们不能(UI中的多个字段为一个隐藏字段生成值-这就是提交的内容。我们不能针对隐藏字段进行验证,因此我们必须为用户可以看到的字段添加仅限UI的验证) 将字段动态添加到页面后,我将在容器上运行以下代码:向ASP中动态创建的元素添加jQuery验证程序规则,jquery,asp.net,jquery-validate,unobtrusive-validation,Jquery,Asp.net,Jquery Validate,Unobtrusive Validation,我在MVC3项目的页面上动态插入了一些表单字段。通常我们会在服务器端添加jQuery验证,但在这种情况下我们不能(UI中的多个字段为一个隐藏字段生成值-这就是提交的内容。我们不能针对隐藏字段进行验证,因此我们必须为用户可以看到的字段添加仅限UI的验证) 将字段动态添加到页面后,我将在容器上运行以下代码: $container.find(".date").rules("add", { required: true, messages: { required: "Th
$container.find(".date").rules("add", {
required: true,
messages: {
required: "The date is required"
}
});
但它不起作用!奇怪的是,禁用上述代码,创建动态元素,然后在浏览器JS控制台中运行代码,但只显示默认的验证消息
我不知所措。有什么想法吗
我使用的是jQuery Validation 1.9.0&一个不引人注目的插件,事实证明,这主要可以在HTML中通过向每个表单元素添加一些属性来完成:
属性名称
data val=“true”
data val required=“message”
<input type='text' name="date" data-val="true" data-val-required="A date is required." />
我想你犯了更简单的错误-比如你的
查找('.date')
实际上什么都没有找到。因为否则,你的代码在我看来很合理。下面是一个按您预期工作的示例:
我能够通过以下方法正确验证代码:
$('form fieldset')
.append('<br>New Field: <input type="text" name="newField"> * Also required')
.find('input[name="newField"]').rules('add', {
required: true,
messages: {
required: 'New field is required'
}
}
);
//create new form element
$('form fieldset').append('<br>New Field: '+
'<input type="text" data-val="true" data-val-required="A date is required." name="newField">'+
' * Also required');
//add new rules to it
$.validator.unobtrusive
.parseElement($('form').find('input[name="newField"]').get(0));
$(“表单字段集”)
.append(“
新字段:*也是必需的”)
.find('input[name=“newField”]”)。规则('add'{
要求:正确,
信息:{
必填项:“需要新字段”
}
}
);
现在,我了解了不引人注目的插件方面的情况(我知道这与ASP.NET有关),下面是您需要做的:
添加新元素后,调用$.validator.unobtrusive.parseElement(newElement)
,它将被添加到表单中。正如您的回答所建议的,您需要在新表单元素中设置data val和data val required属性
所以你最终会得到这样的结果:
$('form fieldset')
.append('<br>New Field: <input type="text" name="newField"> * Also required')
.find('input[name="newField"]').rules('add', {
required: true,
messages: {
required: 'New field is required'
}
}
);
//create new form element
$('form fieldset').append('<br>New Field: '+
'<input type="text" data-val="true" data-val-required="A date is required." name="newField">'+
' * Also required');
//add new rules to it
$.validator.unobtrusive
.parseElement($('form').find('input[name="newField"]').get(0));
//创建新的表单元素
$('form fieldset')。追加('
新字段:'+
''+
“*也必须”);
//添加新规则
$.validator.untrusive
.parseElement($('form').find('input[name=“newField”]).get(0));
此处显示:True,但您没有添加对不引人注目的验证插件的引用-这似乎就是问题所在。我更新了它以包含以下内容:嗯,不仅如此,我向您发送了指向错误JSFIDLE:)的链接,而且,我没有发现这个不引人注目的插件是相关的,我对ASP.NET如何生成表单并使用表单一无所知。。。所以,是的,你靠自己,听起来你找到了一个可行的解决方案。啊,太好了!我可能会使用一个自定义方法来完成这项工作,并一次性将数据属性添加到所选字段中。5.5年后,在将新的局部视图注入编辑器界面时,仍然可以像champ一样工作。最后一行不应该是
$.validator.unobtrusive.parse($(“form”)
?@Kunal不,不需要这样做,parse
函数希望在其中传递CSS选择器字符串,但传递jQuery对象也没有什么害处。这不是必需的。所以7年后我来到这里,很高兴人们仍然觉得这很有用。。。但也有点遗憾的是,人们仍然必须使用jQuery验证:(