我使用标准 MVC3 Razor 视图和不显眼的 Javascript 验证,使用@Html.ValidationSummary
将它们显示在表单顶部。如果标准验证(例如[Required]
)通过,然后我运行一些非常自定义的客户端验证,当用户点击“提交”按钮时会触发该验证。 (验证会检查多个表单元素,以确保检查了正确的一组表单元素等,因此它并不像为单个字段创建新的自定义验证器那么简单)。
我希望我在那里构造的可能错误显示在ValidationSummary
列表,但我不知道如何让错误消息出现在那里。
在客户端:
function YourCustomValidator() {
// do your validation logic here via JavaScript
return true; // or false based on your validation logic
}
$(document).ready(function () {
// take your own form-selector like ("form", this)
$("form", this).first().submit(function () {
return (YourCustomValidator() && $(this).valid());
});
});
或者在服务器端:
认为你有一个这样的模型:
public class Test {
[Required]
[StringLength(100)]
public string FullName { get; set; }
}
当你验证它时:
if(ModelState.IsValid) { // default validations run here
if(/* some custom validations run here, there is an error about "FullName" */){
// you should set the "key" for Model-Error to "FullName"
ModelState.AddModelError("FullName","error-message goes here")
}
if(/* some custom validations run here, the error is global, not on "FullName" */){
// you should set the "key" for Model-Error to an empty-string
ModelState.AddModelError("","error-message goes here")
}
// also you can test for model-errors again like this:
if(ModelState.IsValid) { // if you add any error above, this will be "false"
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)