客户端自定义数据注释validation
我已经创建了一个自定义数据注释来对我的视图模型进行一些validation。 问题是它没有在客户端validation。 这是我的模特:
public class MemberViewModel { [ScaffoldColumn(false)] public int MemberId { get; set; } [Required(ErrorMessage = "Name is required")] public string Name { get; set; } //My custom data annotation [EnforceTrue(ErrorMessage = "You must agree to the Terms and Conditions")] public bool AgreeTerms { get; set; } }
我的数据注释validation码:
public class EnforceTrueAttribute : ValidationAttribute, IClientValidatable { public EnforceTrueAttribute() { } public override bool IsValid(object value) { return value != null && (bool)value == true; } public IEnumerable GetClientValidationRules(ModelMetadata metadata, ControllerContext context) { yield return new ModelClientValidationRule() { ValidationType = "enforcetrue", ErrorMessage = this.ErrorMessageString }; } }
我的控制器方法:
[HttpPost] public ActionResult Index(MemberViewModel viewModel) { Member member = new Member(); TryUpdateModel(member); if (ModelState.IsValid) { _membersRepository.SaveMember(member); return RedirectToAction("Index", "Home"); } return View(viewModel); // validation error, so redisplay same view }
我的观点是:
@using (Html.BeginForm("Index", "Members", FormMethod.Post)) { @Html.HiddenFor(m => m.MemberId) @Html.LabelFor(model => model.Name) @Html.TextBoxFor(model => model.Name) @Html.CheckBoxFor(model => model.AgreeTerms)
@Html.ValidationSummary() }
所以我的所有其他错误消息都会在客户端validation的validation摘要中显示出来。 但对于我的自定义数据注释,错误消息在模型的其余部分有效之前不会显示,并且在您提交表单和页面重新加载之后,错误显示在摘要中。
我还需要做些什么来让它在其他错误的摘要中显示出来吗?
我正在使用C#和ASP.NET MVC 3
最近有同样的问题。 你可以写:
$.validator.addMethod('enforcetrue', function (value, element) { return $(element).is(":checked"); }); $.validator.unobtrusive.adapters.add('enforcetrue', [], function (options) { options.messages['enforcetrue'] = options.message; options.rules['enforcetrue'] = options.params; });
类似的问题这里ASP.NET MVC 3客户端validation
实现Iclientvalidatable只会为生成的html输入添加不显眼的属性。 要在客户端启用validation,您必须编写使用这些不显眼属性的validation器来validation输入。 在这里,您可以在asp.net mvc 3中找到有关客户端和服务器validation的非常好的解释
您需要一个远程validation器链接http://www.devtrends.co.uk/blog/the-complete-guide-to-validation-in-asp.net-mvc-3-part-1