【问题标题】:MVC 3 Custom ValidationAttribute for CheckBoxFor firing twice on client-sideCheckBoxFor 在客户端触发两次的 MVC 3 自定义验证属性
【发布时间】:2011-02-21 18:01:30
【问题描述】:

我将列出代码来解释整个情况,然后提出问题的描述:

在我的视图模型中,我有一个布尔属性来跟踪用户是否接受了条款:

 [MustBeTrue(ErrorMessageResourceType = typeof(ErrorMessages), ErrorMessageResourceName = "MustAccept")]
 public bool HasAuthorizedBanking { get; set; }

如您所见,我创建了一个自定义验证属性来处理这个称为 MustBeTrue 来处理复选框,因为 [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;
    }
}

然后我将带有 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。
  • 为了跟踪这个方法何时被调用,我简单地设置了一个 alert(checked);在 jQuery Validator 方法“checkrequired”中。

问题:当复选框被选中/取消选中时,'checkrequired' 方法被触发一次。但是,当单击“下一步”按钮并开始验证所有输入元素时,无论复选框是否被选中,都会触发两次。 有趣,如果勾选,第一次验证返回true,第二次返回false(这第二次返回false是我的主要问题——页面不会验证,不允许你继续下一个步)。此外,当它被选中并单击 Next 时 - ValidationMessageFor 消息会消失,就好像它是有效的一样。

编辑:我有另一个自定义属性用于在 jQuery DatePicker 文本框中验证年龄,虽然它以完全相同的方式实现 - 它只在相同条件下触发一次。

【问题讨论】:

    标签: c# validation asp.net-mvc-3 jquery-validate


    【解决方案1】:

    事实证明,问题在于 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
    

    【讨论】:

      猜你喜欢
      • 2014-05-26
      • 1970-01-01
      • 2014-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-12
      • 2017-05-08
      • 1970-01-01
      相关资源
      最近更新 更多