...

/

Validation and Validation Attributes

Validation and Validation Attributes

In this lesson, we will learn how to perform user input validation on the server-side.

In the previous lessons we learned that binders perform validation on the right string format of the input parameters during action parameters binding. Actually, they just try to convert the input strings into the types of the target parameters. When the conversion fails errors are added to the controller ModelState. Other validation checks can be added to each property of a target ViewModel by decorating it with particular data annotations inherited from the ValidationAttribute class. Moreover, the action method code can perform further “manual checks” adding all errors to the ModelState.

Each possible validation option is discussed in detail in a dedicated lesson section.

Wrong format errors

For each wrong formatted input, the binder that processes it adds an entry to the ModelState. Its key is the path in the target object tree or the name of a simple type parameter and whose value is the list of the messages associated with all errors discovered on the input string.

The attempted string value is placed in a property of this entry, too. This way the attempted value can be used to fill the same input field it comes from when the same page is returned to the user so that it can correct all errors.

Thus for instance, if the date string matched with the Salary property of a customer is ill-formatted, such as a decimal value of say “100%.2”, then an entry is created as follows:

  • The entry key is “Salary”.
  • The error messages list will contain a unique message like “The field ‘Salary’ must be a number”.
  • The attempted value is “100%.2”.

Entries in the ModelState are created for each input field that is used to fill a property or a parameter when no error is detected, but, when there are no errors the list of errors is empty.

When the controller returns a view for enabling the user to correct all errors, the “Salary” key is used to locate the input in error. The attempted value is used to fill the input, while the ...

Access this course and 1400+ top-rated courses and projects.