客户端自定义注释验证无效

时间:2014-06-19 03:03:24

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

我正在尝试使用ASP.NET MVC应用程序中的自定义注释进行客户端验证。对不起有点冗长的帖子。

以下是自定义属性:

public class CustomStringLengthAttribute : ValidationAttribute, IClientValidatable
{
    public int MaxLength { get; private set; }
    public int MinLength { get; set; }

    public CustomStringLengthAttribute(int maxLength)
        : base(GetDefaultErrorMessage)
    {
        MaxLength = maxLength;
    }

    private static string GetDefaultErrorMessage()
    {
        return "Max length {1}";
    }

    public override string FormatErrorMessage(string name)
    {
        return string.Format(ErrorMessageString, name, MaxLength, MinLength);
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        ...

        if (length > MaxLength || length < MinLength)
            return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));

        return ValidationResult.Success;
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule();
        rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());
        rule.ValidationType = "customstringlength";
        rule.ValidationParameters.Add("max", MaxLength);
        rule.ValidationParameters.Add("min", MinLength);

        yield return rule;
    }
}

我在视图模型中使用该属性:

[CustomStringLength(25)]
public virtual string BillAddress1 { get; set; }

数据属性似乎按以下方式生成:

<input data-val="true" data-val-customstringlength="Max length 25" data-val-customstringlength-max="25" data-val-customstringlength-min="0" id="BillAddress1" name="BillAddress1" type="text" value="">

客户端验证开始了,但我得到了#34; Uncaught TypeError:无法读取属性&#39; call&#39;未定义&#34;在jquery.validate.js

这是来自&#34; check:function(element)...&#34;在jquery.validate.js中 - 方法变量是&#34;未定义&#34;:

jquery.validate.js, check: function(element) ...

查看rules变量解释了为什么方法变量未定义 - 由于某种原因,包含min和max参数的数组是&#34; undefined&#34;而不是被命名为&#34; customstringlength&#34;:

jquery.validate.js, check: function(element) ...

但是为什么它是&#34;未定义&#34; ??

这是我的customValidation.js,我在其中添加了适配器等:

(function ($) {
    if ($.validator && $.validator.unobtrusive) {

        $.validator.unobtrusive.adapters.addMinMax("customstringlength", "min", "max");

        $.validator.addMethod("customstringlength", function (value, element, min, max) {
            if (value) {
                if (value.length < min || value.length > max) {
                    return false;
                }
            }
            return true;
        });
    }
}(jQuery));

这是我调用表单验证的地方:

function validateForm(form) {
    prepareValidationScripts(form);
    var validator = $.data(form[0], 'validator');
    return validator.form();
}

function prepareValidationScripts(form) {
    if (form.executed)
        return;
    form.removeData("validator");
    $.validator.unobtrusive.parse(document);
    form.executed = true;
}

我一直盯着这个太久了 - 我错过了什么?

1 个答案:

答案 0 :(得分:1)

我终于有了这个工作!我决定不尝试使用“方便”的addMinMax适配器,而是编写自定义适配器。这是更新的customValidation.js(其他一切保持不变):

(function ($) {
    if ($.validator && $.validator.unobtrusive) {

        $.validator.unobtrusive.adapters.add('customstringlength', ['min', 'max'], function(options) {
            options.rules['customstringlength'] = {
                min: options.params.min,
                max: options.params.max,
            };
            options.messages['customstringlength'] = options.message;
        });

        $.validator.addMethod('customstringlength', function (value, element, params) {
            if (value) {
                if (value.length < params.min || value.length > params.max) {
                    return false;
                }
            }
            return true;
        });
    }
}(jQuery));