Not Equal C && !=C && 不等于西
RSS icon Email icon Home icon
  • Custom Validation for MVC 3 Model Example 1: Positive Integer

    Posted on January 7th, 2012 Sean 2 comments

    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:

    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:

    Then, we will create validation adapter to enable client side validation

    Last thing we need to do is register the adapter in “Application_Start” function of “Global.asax” file:

    Now, we can use the custom validation attribute “PositiveInteger” for the model “Prodcut”

    1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)

    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