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<ModelClientValidationRule> 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.