Asp.Net MVC和自定义不显眼的验证

时间:2013-09-06 16:42:34

标签: jquery asp.net-mvc unobtrusive-validation

我正在尝试使用自定义规则“mustbetrue”。松散地基于this question: 我的问题是,当我提交表单时,客户端验证不会给我一个错误(不会显示验证文本)。 另外我在jscript验证方法中设置了一个断点,它永远不会被触发。添加适配器的连接代码会被触发。控制台中没有错误。

我做错了什么?

这就是我的服务器端:

public class MustBeTrueAttribute : ValidationAttribute, IClientValidatable
{
    public override bool IsValid(object value)
    {
        if (value == null) return false;
        try
        {
            return Convert.ToBoolean(value);
        }
        catch (InvalidCastException)
        {
            return false;
        }
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata,
                                                                           ControllerContext context)
    {
        yield return new ModelClientValidationRule
            {
                ErrorMessage = this.ErrorMessage,
                ValidationType = "mustbetrue"
            };
    }
}

public class MustBeTrueAttributeAdapter : DataAnnotationsModelValidator<MustBeTrueAttribute>
{
    public MustBeTrueAttributeAdapter(ModelMetadata metadata, ControllerContext context, MustBeTrueAttribute attribute)
        : base(metadata, context, attribute)
    {
    }

    public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
    {
        return new[] { new ModelClientValidationMustBeTrueRule(ErrorMessage) };
    }
}

public class ModelClientValidationMustBeTrueRule : ModelClientValidationRule
{
    public ModelClientValidationMustBeTrueRule(string errorMessage)
    {
        ErrorMessage = errorMessage;
        ValidationType = "mustbetrue";
    }
}

并在global.asax

    protected void Application_Start()
    {
        // stuff
        DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(MustBeTrueAttribute), typeof(MustBeTrueAttributeAdapter));
        // stuff
    }

并在对象上:

[MustBeTrue(ErrorMessageResourceName = "Register_TermsNotAccepted", ErrorMessageResourceType = typeof(Resources.Global))]
public bool AcceptedTerms { get; set; }

客户方:

$(document).ready(function () {
    jQuery.validator.addMethod("mustbetrue", function (value, element) {
        if (!this.depend(param, element))
            return "dependency-mismatch";
        return element.checked;
    });
    jQuery.validator.unobtrusive.adapters.addBool("mustbetrue", "mustbetrue");
});

以及输出的相关HTML:

<input data-val="true" data-val-mustbetrue="You must accept the terms and conditions" data-val-required="The AcceptedTerms field is required." id="AcceptedTerms" name="AcceptedTerms" type="checkbox" value="true" class="valid">

1 个答案:

答案 0 :(得分:1)

如果您已经检查过启用了客户端验证(在配置或代码中),那么我想这是因为您在不显眼的验证脚本解析之后添加适配器 html see my answer here for details and possible options