我使用标准的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" } }
原文地址:https://www.jb51.cc/aspnet/253748.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。