我正在使用标准 MVC3 Razor View 和不显眼的 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"
}
}
关于asp.net-mvc-3 - 将错误消息添加到 @Html.ValidationSummary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7882008/