Asp .Net MVC DataAnnotation Range Attribute

Download Source

So far, we have looked at a few DataAnnotation attributes namely, Required, Compare and Display. Following are the links to these blogs posts.

In this short blog post we will look at another important DataAnnotaion attribute, [Range].

Along with all the other Asset details, let's say we want to capture the Year in which the asset was purchased. We can simply add a new property in our model and Modify the View to have a new input field. However we have a requirement that value for this field must be between certain range.

This is the very good example to utilize yet another DataAnnotation attribute named Range. As the name suggest this attribute helps us validate user input between certain range. The first parameter of this attribute is the Minimum possible value and the second parameter is the Maxmimum possible value for the field.

Let's go ahead and make changes to our Model class so that it looks something like below.

Range Attribute

Notice the highlighted Range attribute with parameters 2007 and 2013. That means when user is filling out the value for this field the value must be between 2007 and 2013 inclusive. That means 2007 and 2013 will also be consider a valid entry.

Modify the Create view so it can accept the value of Year Purchased field.

EditorFor HtmlHelper

Go ahead and run the application. Try inserting the value that is not between 2007 to 2012. And you should see the appropriate error message as highlighted below.

EditorFor HtmlHelper

Now, let' examine what types of data-* attributes were generated as a result of this Range attribute.

EditorFor HtmlHelper

And as you must have anticipated, the @Html.EditorFor has resulted into two new data-* attributes.

  • data-val-range-min="2007" [Minimum valid value for the field, first parameter of Range attribute]
  • data-val-range-max="2013" [Minimum valid value for the field, second parameter of Range attribute]

So, these are some out of the box DataAnnotation attributes provided by System.ComponentModel.DataAnnotations namespace. In future we will look at how we can construct our own DataAnnotation attributes.