MaxLength Attribute not generating client-side validation attributes

前端 未结 11 544
北荒
北荒 2020-11-30 02:41

I have a curious problem with ASP.NET MVC3 client-side validation. I have the following class:

public class Instrument : BaseObject
{
    public int Id { get         


        
11条回答
  •  温柔的废话
    2020-11-30 03:26

    I know I am very late to the party, but I finaly found out how we can register the MaxLengthAttribute.

    First we need a validator:

    public class MaxLengthClientValidator : DataAnnotationsModelValidator
    {
        private readonly string _errorMessage;
        private readonly int _length;
    
    
        public MaxLengthClientValidator(ModelMetadata metadata, ControllerContext context, MaxLengthAttribute attribute)
        : base(metadata, context, attribute)
        {
            _errorMessage = attribute.FormatErrorMessage(metadata.DisplayName);
            _length = attribute.Length;
        }
    
        public override IEnumerable GetClientValidationRules()
        {
            var rule = new ModelClientValidationRule
            {
                ErrorMessage = _errorMessage,
                ValidationType = "length"
            };
    
            rule.ValidationParameters["max"] = _length;
            yield return rule;
        }
    }
    

    Nothing realy special. In the constructor we save some values from the attribute. In the GetClientValidationRules we set a rule. ValidationType = "length" is mapped to data-val-length by the framework. rule.ValidationParameters["max"] is for the data-val-length-max attribute.

    Now since you have a validator, you only need to register it in global.asax:

    protected void Application_Start()
    {
        //...
    
        //Register Validator
        DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(MaxLengthAttribute), typeof(MaxLengthClientValidator));
    }
    

    Et voila, it just works.

提交回复
热议问题