[英]Client-side custom data annotation 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; }
}
我的数据注释验证码:
public class EnforceTrueAttribute : ValidationAttribute, IClientValidatable
{
public EnforceTrueAttribute() { }
public override bool IsValid(object value)
{
return value != null && (bool)value == true;
}
public IEnumerable<ModelClientValidationRule> 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)
<div class="editor-label">@Html.LabelFor(model => model.Name)</div>
<div class="editor-field">@Html.TextBoxFor(model => model.Name)</div>
<div class="editor-field">@Html.CheckBoxFor(model => model.AgreeTerms) <label for="AgreeTerms">I agree to the Terms and Conditions</label></div>
<p>
<input type="submit" value="Submit" />
</p>
@Html.ValidationSummary()
}
所以我的所有其他错误消息都会在客户端验证的验证摘要中显示出来。 但是对于我的自定义数据注释,错误消息在模型的其余部分有效之前不会显示,并且在您提交表单和页面重新加载之后,错误显示在摘要中。
我还需要做些什么来让它在其他错误的摘要中显示出来吗?
我正在使用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客户端验证
实现Iclientvalidatable只会为生成的html输入添加不显眼的属性。 要在客户端启用验证,您必须编写使用这些不显眼的属性验证输入的验证器。 在这里,您可以在asp.net mvc 3中找到客户端和服务器验证的非常好的解释
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.