在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
第一步修改 实体模型
public class UserInfo { public int Id { get; set; } [Required] [StringLength(20,ErrorMessage="名字太长了或者太短了",MinimumLength=4)] public string Name { get; set; } [RegularExpression(@"([2-5]\d)",ErrorMessage="年龄在20-50之间")] public int Age { get; set; } } 注意:需要添加 System.ComponentModel.DataAnnotations; 引用 第二步增加Filter
public class ValidationAttribute : ActionFilterAttribute { public override void OnActionExecuting(HttpActionContext actionContext) { if (!actionContext.ModelState.IsValid) { actionContext.Response = actionContext.Request.CreateErrorResponse( HttpStatusCode.BadRequest, actionContext.ModelState); } } }
using System.Web; using System.Web.Http.Filters; using System.Web.Http.ModelBinding; using System.Web.Http.Controllers; using System.Net.Http; using System.Net; using Newtonsoft.Json.Linq;
第三步 注册Filter config.Filters.Add(new Filters.ValidationAttribute());
第四步 编写页面
<link href="Content/Site.css" rel="stylesheet" type="text/css" /> <script src="Scripts/jquery-1.7.1.min.js" type="text/javascript"></script> <script src="Scripts/knockout-2.1.0.js" type="text/javascript"></script> <script src="Scripts/jquery.validate.min.js" type="text/javascript"></script> <script src="Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>
拷贝HTMLPage2的内容稍作修改
<label for="text"> 名称</label> <input id="name" name="name" data-val="true" data-val-required="是不是忘记输入名称了?" type="text" value="" /> <span class="field-validation-valid" data-valmsg-for="name" data-valmsg-replace="true"> </span> <label for="text"> 年龄</label> <input id="age" name="age" type="text" data-val="true" data-val-required="年龄也是必须输入的哦!" value="" /> <span class="field-validation-valid" data-valmsg-for="age" data-valmsg-replace="true"> </span> <br /> <button type="submit"> Submit</button>
增加js,这段js是将服务返回的错误消息进行显示 $.validator.addMethod("failure", function () { return false; }); $.validator.unobtrusive.adapters.addBool("failure"); $.validator.unobtrusive.revalidate = function (form, validationResult) { $.removeData(form[0], 'validator'); var serverValidationErrors = []; for (var property in validationResult) { var elementId = property.toLowerCase(); elementId = elementId.substr(elementId.indexOf('.') + 1); var item = form.find('#' + elementId); serverValidationErrors.push(item); item.attr('data-val-failure', validationResult[property][0]); jQuery.validator.unobtrusive.parseElement(item[0]); } form.valid(); $.removeData(form[0], 'validator'); $.each(serverValidationErrors, function () { this.removeAttr('data-val-failure'); jQuery.validator.unobtrusive.parseElement(this[0]); }); }
增加服务器返回错误消息显示操作 400 /* BadRequest */: function (jqxhr) { var validationResult = $.parseJSON(jqxhr.responseText); $.validator.unobtrusive.revalidate(form, validationResult.ModelState); }
2 输入不合法 本篇完整代码:/Files/risk/web api 5/MvcApplication1.rar |
请发表评论