我使用标准的MVC3 Razor视图与不引人注目的Javascript验证,使用@ Html.ValidationSummary来显示它们在表单的顶部。如果标准验证(例如[必需])通过,那么我将在用户点击Submit按钮时运行一些非常自定义的客户端验证。 (验证会查看许多表单元素,以确保其正确的一组已经被检查等等,因此它不像为单个字段创建新的自定义验证器那么简单)。
解决方法
在客户端:
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" } }