• Now Online : 20
  • admin@codemyne.net

Validations with Model In MVC:In this post we'll learn how to use the Data Annotation validators to perform validations in an ASP.NET MVC application. System.ComponentModel.DataAnnotations assembly can be used to validate the individual fields in the data model. The advantage of using DataAnnotations is we can simply add one or more attributes to a class property.

Using DataAnnotations Validator Attributes: There are various attributes in DataAnnotations which can be used as a validator as shown below

  • Required - makes a property as required

  • Range - Checks whether the value falls between specified range of values

  • ReqularExpression - Verifies whetehr the given value matches with the specified regular expression

  • StringLength - Enables to specify a maximum length of a string property

  • Validation - It is a base class for all validation attributes

DisplayName attribute: The DisplayName attribute enables you to modify the name of the property when the property is displayed in an error message. For example instead of displaying the error message 'The UnitPrice field is required' we can dispaly 'The Price field is required' , if used DisplayName attribute as shown below

Products Model

ModelState

ModelState is a property of a Controller class which gets the model state dictionary object. This dictionary contains the collection that has the key and values of the data submitted to the server in POST method. Along with these values it also contains error messages for each value to which validation attributes are defined in model.

Whenever the ModelState is active in server,the properties of the model are validated according to the validation attributes that are associated with them. And if any of the property is invalid it will be added to the error list. And the property ModelState.IsValid will be set to false as shown below.

ModelState

For instance, take Account Controller class go to Login action (which is overloaded with LoginViewModel) and put a breakpoint at ModelState.IsValid. Start debug->Start Debugging (or press F5) and go to Login page and click on LogIn button. When the control comes to debug point expand the ModelState then the screen will be as shown below.

ModelStateDebug

From the above screen, you can find different properties like Count, IsValid, Keys, Values of ModelState. The keys property is a collection of all the keys in the dictionary. Each of the Value property in Values is an instance of ValueProviderResult which contains actual value submitted to controller action.

ModelState.Errors: Returns a ModelErrorCollection object that contains any errors that occurred during model binding. ModelErrorCollection is an instance of ModelError class which represents an error.

ModelState.IsValid: Gets a value that indicates whether this instance of the model-state dictionary is valid(as per Msdn). Basically, IsValid will be false if there is any issue with the data posted to the server based on Data Annotations added to the properties of the model.

For instance if a model property is defined with an attribute [Required], and that property is empty when the data is posted to the server, the ModelState.IsValid will be false.

Displaying model errors in View

As of now we have seen how to add validations to the model properties and how to check and get these errors using ModelState. These errors are need to be passed to the view from controller to show to the end user. For this two html helpers ValidationMessageFor and ValidationSummary can be used.

  • ValidationMessageFor Returns the HTML markup for a validation-error message for each data field that is represented by the specified expression. It displays a message that usualy specified on top of the peoperty in view model. This can be overriden with custom message.

  • ValidationSummary Returns an unordered list (ul element) of validation messages that are in the ModelStateDictionary object. i.e.,The ValidationSummary method displays a list of all validation messages on the page.

Usage of ValidationMessageFor and ValidationSummary can be seen from the image shown below.

Note:The Boolean parameter using (with a value of true) tells the helper to exclude property-level errors. In other words, the summary displays only the errors in ModelState associated with the model itself, and exclude any errors associated with a specific model property. We will see how to customize model errors in another article.

Comments/Suggestions are invited. Happy coding......!

Comments Post a Comment