Required Data Annotation attribute in MVC 3 Razor

  1. The Required Data Annotation attribute is used to apply validations. 
  2. This attribute makes the property of model mandatory for user. 
  3. When the value is not provided for the property, it gives an error.
Example 1 :

We have applied Required Data Annotation attribute to the FirstName property. In order to use this property in your model or ViewModel, you have to add reference of using System.ComponentModel.DataAnnotations;

UI :

When value is not entered for FirstName and form is posted, it gives us error as shown above. The message shown is the default message. It picks the name of the property i.e. FirstName in this case.

Example 2 :

In this case, we have also mentioned the ErrorMessage. When the value is not provided, the above error message will be displayed.

UI :

As shown above, the error message is displayed as provided by us.

Example 3 :

The preceding code assumes we have a resource file in the project by the name Multi.resx with the appropriate entry inside (FirstName_Required). When validation fails, it picks error message from resource file. This helps to display error messages in multiple languages.

Resource :

The above is the message with FirstName_Required key. This key is picked for FirstName validation.

UI :

As shown in above image, the validation fails for the FirstName property and the message is picked from Resource files.


Post a Comment