肖恩D++
Not Equal C && !=C && 不等于西
-
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.
Read the rest of this entry »
3,067 views
Recent Comments