I had the same problem as Kenchi. I wanted to use both [Min] and [Max] at the same time so that I could have a separate error message for each type of error instead of a range. I also ran into ...
Validation type names in unobtrusive client validation rules must be unique. The following validation type was seen more than once: range
Because they decided to use the same validation name for both types!
I got around this by saving min and creating my own Int Max.
Add this class somewhere, ideally to the CustomerValidation class
public class MaximumDecimalCheck : ValidationAttribute, IClientValidatable { private readonly int _max; private readonly string _defaultErrorMessage = ""; public MaximumDecimalCheck(int max, string defaultErrorMessage) : base(defaultErrorMessage) { _max = max; _defaultErrorMessage = defaultErrorMessage.Replace("{0}", _max.ToString()); } protected override ValidationResult IsValid(object value, ValidationContext validationContext) { if (value == null) return null; int intValue; bool parsedDecimal = int.TryParse(value.ToString(), out intValue); if (parsedDecimal) { if (intValue < _max) { return ValidationResult.Success; } } return new ValidationResult(_defaultErrorMessage); } public override string FormatErrorMessage(string name) { return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString, _max); } public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) { var modelClientValidationRule = new ModelClientValidationRule(); modelClientValidationRule.ValidationType = "checkmaxint"; modelClientValidationRule.ErrorMessage = _defaultErrorMessage; modelClientValidationRule.ValidationParameters.Add("maxint", _max.ToString()); return new List<ModelClientValidationRule> { modelClientValidationRule }; } }
Then in your model object
[Required(ErrorMessage = "Monthly income (after tax) required")] [DataType(DataType.Currency)] [Display(Name = "Monthly income (after tax)")] [Min(200, ErrorMessage = "You do not earn enough")] [MaximumDecimalCheck(10000, "You earn to much a month")] public decimal? MonthlyIncomeAfterTax { get; set; }
the type of the property can be decimal, int, etc .... however, it will parse it only as an int.
I was not able to create a static decimal type, so gave up so quickly, if someone can answer this question, I would be very pleased.
After adding the notation, refer to the following javascript.
(function ($) { jQuery.validator.unobtrusive.adapters.add("checkmaxint", ['maxint'], function (options) { options.rules["checkmaxint"] = options.params; options.messages["checkmaxint"] = options.message; }); jQuery.validator.addMethod("checkmaxint", function (value, element, params) { var maxValue = params.maxint; var inputValue = value; var parsedInt = parseInt(inputValue); if (isNaN(parsedInt)) { return false; } else if (parsedInt > maxValue) { return false; } else { return true; } }); } (jQuery));
I hope this helps.