c# – MVC 3 CheckBox的自定义ValidationAttribute在客户端触发
我将列出代码来解释整个情况然后提出问题的描述:
在我的View Model中,我有一个布尔属性来跟踪用户是否接受了术语: [MustBeTrue(ErrorMessageResourceType = typeof(ErrorMessages),ErrorMessageResourceName = "MustAccept")] public bool HasAuthorizedBanking { get; set; } 正如您所看到的,我已经创建了一个自定义验证属性来处理这个名为MustBeTrue的处理Checkbox,因为[Required]是currently not working for client-side validation on Checkboxes in MVC 3 public class MustBeTrueAttribute : ValidationAttribute,IClientValidatable { protected override ValidationResult IsValid(object value,ValidationContext validationContext) { if ((bool)value) return ValidationResult.Success; return new ValidationResult(String.Format(ErrorMessageString,validationContext.DisplayName)); } public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata,ControllerContext context) { var rule = new ModelClientValidationRule { ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),ValidationType = "truerequired" }; yield return rule; } } 然后我在我的View中添加一个带有ValidationMessage的CheckBoxFor: @Html.CheckBoxFor(model => model.HasAuthorizedBanking) @Html.ValidationMessageFor(model => model.HasAuthorizedBanking,"",new { @class = "validationtext" }) 为了实现这个客户端,我创建了一个jQuery验证器方法,并添加了一个不显眼的适配器: // Checkbox Validation jQuery.validator.addMethod("checkrequired",function (value,element) { var checked = false; checked = $(element).is(':checked'); return checked; },''); jQuery.validator.unobtrusive.adapters.addBool("truerequired","checkrequired"); 在我看来,注册过程中的所有步骤都在一个页面上,元素被隐藏并通过jQuery显示并使用jQuery Validation进行验证.单击“下一步”按钮时,将触发页面上的每个输入元素以进行验证: var validator = $("#WizardForm").validate(); // obtain validator var anyError = false; $step.find("input").each(function () { if (!validator.element(this)) { // validate every input element inside this step anyError = true; } }); if (anyError) return false; 笔记: >我的模型中只有一个属性具有MustBeTrue属性,并且只有一个CheckBoxFor&在整个页面上匹配ValidationMessageFor. 问题:当选中/取消选中复选框时,会触发’checkrequired’方法一次.但是,当单击“下一步”按钮并且我们启动以验证所有输入元素时,无论是否选中该复选框,都会触发两次.有趣的是,如果选中它,第一个验证返回true,第二个验证返回false(第二个错误返回是我的主要问题 – 页面将不会验证,它将不允许您继续下一步).此外,当选中它并单击Next时 – ValidationMessageFor消息将消失,就好像它是有效的一样. 编辑:我有另一个自定义属性用于在jQuery DatePicker文本框中验证Age,虽然它以完全相同的方式实现 – 它只在相同的条件下触发一次. 解决方法
事实证明,问题是Html.CheckBoxFor正在生成与复选框同名的第二个输入元素,如下所述:
http://forums.asp.net/t/1314753.aspx
<input data-val="true" data-val-required="The HasAuthorizedBanking field is required." data-val-truerequired="You must accept to continue." id="bankingtermscheckbox" name="HasAuthorizedBanking" type="checkbox" value="true" /> <input name="HasAuthorizedBanking" type="hidden" value="false" /> 修复是将jQuery选择器更改为仅查看其类型未隐藏的输入元素: $step.find(':input:not(:hidden)').each(function () { // Select all input elements except those that are hidden if (!validator.element(this)) { // validate every input element inside this step anyError = true; } }); if (anyError) return false; // exit if any error found (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |