添加mvc3 Unobtrusive验证最小/最大验证器

时间:2011-03-25 12:16:07

标签: asp.net asp.net-mvc asp.net-mvc-3

我正在尝试为我的自定义类型实现客户端验证,但是我不确定如何为最小/最大验证器执行此操作。

模型:

[MultilanguagePropertyRequired(ErrorMessageResourceName = "fld_Description_val_Required", ErrorMessageResourceType = typeof(Resources.Service.Controllers.Firm))]
[MultilanguagePropertyStringLength(1000, MinimumLength = 150, ErrorMessageResourceName = "fld_Description_val_MinLength_lbl", ErrorMessageResourceType = typeof(Resources.Service.Controllers.Firm))]      
[Display(Name = "fld_Description_lbl", ResourceType = typeof(Resources.Service.Controllers.Firm))]
public MultilanguageProperty<string> Description
{
    get
    {
        return this.GetMultilanguageProperty("Description", string.Empty, this);
    }

    set
    {
        this.SetMultilanguageProperty("Description", value);
    }
}

这是我的自定义字符串长度属性,扩展了“StringLegth”:

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true)]
public class MultilanguagePropertyStringLengthAttribute : StringLengthAttribute, IClientValidatable
{
    public MultilanguagePropertyStringLengthAttribute(int length) : base(length)
    {
    }

    public override bool IsValid(object value)
    {
        string strValue = (string)(value as MultilanguageProperty<string>).Value;

        return base.IsValid(strValue);
    }

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

然后我认为我有这个: ..

<script type="text/javascript">
    (function ($) {
        $.validator.unobtrusive.adapters.addBool("multilanguagerequired", "required");
        $.validator.unobtrusive.adapters.addMinMax("multilanguagestringlength", "minlength", "maxlength");
    } (jQuery));
</script>

...

哪个不起作用。我在这里错过了什么吗? 感谢

3 个答案:

答案 0 :(得分:4)

无需自定义客户端验证。你可以尝试这样的事情:

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public sealed class ValidatePasswordLengthAttribute : ValidationAttribute, IClientValidatable {
    private const string _defaultErrorMessage = "'{0}' must be between {1} and {2} characters long.";
    private readonly int _minCharacters, _maxCharacters;

    public ValidatePasswordLengthAttribute(int minLength, int maxLength)
        : base(_defaultErrorMessage) {
            _minCharacters = minLength;
            _maxCharacters = maxLength;
    }

    public override string FormatErrorMessage(string name) {
        return String.Format(CultureInfo.CurrentCulture, ErrorMessageString,
            name, _minCharacters, _maxCharacters);
    }

    public override bool IsValid(object value) {
        string valueAsString = value as string;
        return (valueAsString != null && valueAsString.Length >= _minCharacters && valueAsString.Length <= _maxCharacters);
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) {
        return new[]{
            new ModelClientValidationStringLengthRule(FormatErrorMessage(metadata.GetDisplayName()), _minCharacters, _maxCharacters)
        };
    }
}

它来自内置的MVC3互联网项目模板。

答案 1 :(得分:3)

我以不同的方式解决类似的问题,但是,嘿,试试这段代码的某些部分!我的意思是GetClientValidationRules()方法用于字符串长度验证。

public sealed class MyStringLengthAttribute : StringLengthAttribute, IClientValidatable
    {
        private int? labelId;

        public MyStringLengthAttribute(int label, int maximumLength)
            : base(maximumLength)
        {
            labelId = label;
        }

        public override string FormatErrorMessage(string name)
        {
            if (labelId.HasValue)
            {
                return String.Format(MyLabel.Label(labelId.Value), name);
            }
            return String.Format(MyLabel.Default("FieldTooLong_Validation", "Field {0} is too long"), name);
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            StringLengthAttributeAdapter adapt = new StringLengthAttributeAdapter(metadata,context, this);
            return adapt.GetClientValidationRules();
        }
    }

我使用.NET框架中找到的Adapter类,不需要自定义Javascript工作。

如果您仍想进行自定义JS部分http://itmeze.com/2010/12/06/checkbox-has-to-be-checked-with-unobtrusive-jquery-validation-and-asp-net-mvc-3/

,请按照此步骤操作

答案 2 :(得分:1)

我也有同样的问题。您缺少GetClientValidationRules中的ValidationParameters:

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
    var rule = new ModelClientValidationRule
                     {
                         ErrorMessage = this.ErrorMessage,
                         ValidationType = "dayrange"
                     };
    rule.ValidationParameters.Add("min", _minimumDays);
    rule.ValidationParameters.Add("max", _maximumDays);
    yield return rule;
}

我仍然遇到jQuery.validator和jQuery.validator.unobtrusive.adapters之间的连接问题,但这里是代码。希望它有所帮助:

    $(function () {
      jQuery.validator.addMethod('dayRange', function (value, element, param) {
         if (!value) return false;
         var valueDateParts = value.split(param.seperator);
         var minDate = new Date();
         var maxDate = new Date();
         var now = new Date();
         var dateValue = new Date(valueDateParts[2],
                            (valueDateParts[1] - 1),
                             valueDateParts[0],
                             now.getHours(),
                             now.getMinutes(),
                             (now.getSeconds()+5));

         minDate.setDate(minDate.getDate() - parseInt(param.min));
         maxDate.setDate(maxDate.getDate() + parseInt(param.max));

         return dateValue >= minDate && dateValue <= maxDate;
    });

    jQuery.validator.unobtrusive.adapters.addMinMax('dayrange', 'minlength', 'maxlength', 'dayrange');

  }(jQuery));