Custom Validation for MVC 3 Model Example 1: Positive Integer

When 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:

C#

1

2

3

4

5

6

7

8

publicclassProduct

{

[Required(ErrorMessage="Number of Stock is Required")]

[RegularExpression("^\\d+$",ErrorMessage="Must be a Positive Non-decimal Number")]

publicintNumberOfStock{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: