Min/Max-value validators in asp.net mvc

前端 未结 4 1835
时光说笑
时光说笑 2020-12-04 14:56

Validation using attributes in asp.net mvc is really nice. I have been using the [Range(min, max)] validator this far for checking values, like e.g.:



        
4条回答
  •  时光取名叫无心
    2020-12-04 15:26

    jQuery Validation Plugin already implements min and max rules, we just need to create an adapter for our custom attribute:

    public class MaxAttribute : ValidationAttribute, IClientValidatable
    {
        private readonly int maxValue;
    
        public MaxAttribute(int maxValue)
        {
            this.maxValue = maxValue;
        }
    
        public IEnumerable GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule();
    
            rule.ErrorMessage = ErrorMessageString, maxValue;
    
            rule.ValidationType = "max";
            rule.ValidationParameters.Add("max", maxValue);
            yield return rule;
        }
    
        public override bool IsValid(object value)
        {
            return (int)value <= maxValue;
        }
    }
    

    Adapter:

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

    Min attribute would be very similar.

提交回复
热议问题