-
Custom Validation for MVC 3 Model Example 1: Positive Integer
Posted on January 7th, 2012 2 commentsWhen you define a property of the model, you can always put some MS’s attributes to validate the data, like “Required”, “Range”. Also you can use custom validation via expression or creating new attribute class. For example, the “NumberOfStock” for “Product” must be an integer and positive.
Actually to accomplish this validation is quite easy, if use regular expression:12345678public class Product{[Required(ErrorMessage = "Number of Stock is Required")][RegularExpression("^\\d+$", ErrorMessage = "Must be a Positive Non-decimal Number")]public int NumberOfStock{ get; set; }/******** Other Properties **************/}The way showed above will be good enough if you only have a few models or a small application. For a big project, you might want to create your own attribute instead of using expression. The advantage of dong this is easy to centralize (if you have many custom validations), and easy to debug.
First, we need to create custom attribute class:123456789101112131415161718192021222324[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]public class PositiveIntegerAttribute : ValidationAttribute{public PositiveIntegerAttribute(): base("Must be a Positive Non-decimal Number"){}public override bool IsValid(object value){if (value == null){return true;}int num;if (int.TryParse(value.ToString(), out num)){if (num >= 0)return true;}return false;}}Then, we will create validation adapter to enable client side validation
123456789101112131415161718192021222324public class PositiveIntegerValidator : DataAnnotationsModelValidator{public PositiveIntegerValidator(ModelMetadata metadata, ControllerContext context, PositiveIntegerAttribute attribute): base(metadata, context, attribute){}public override IEnumerable GetClientValidationRules(){return new[] { new PositiveIntegerClientValidationRule(ErrorMessage) };}}public class PositiveIntegerClientValidationRule : ModelClientValidationRule{private const string Regex = @"^\+?\d+$";public PositiveIntegerClientValidationRule(string errorMessage){ErrorMessage = errorMessage;ValidationType = "regex";ValidationParameters["pattern"] = Regex;}}Last thing we need to do is register the adapter in “Application_Start” function of “Global.asax” file:
123456protected void Application_Start(){/**********Other code************/DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(Library.PositiveIntegerAttribute), typeof(Library.PositiveIntegerValidator));}Now, we can use the custom validation attribute “PositiveInteger” for the model “Prodcut”
12345678public class Product{[Required(ErrorMessage = "Number of Stock is Required")][PositiveInteger]public int NumberOfStock{ get; set; }/******** Other Properties **************/}
Leave a Reply
2 Comments on "Custom Validation for MVC 3 Model Example 1: Positive Integer"
“^\+?\d+$” – Why the leading slashes (\+)?
Not needed actually. It must be the leftover by copying from my other expression for signed integer, thanks for pointing it out