Server-Side Validation
Let's continue with the application that we built in the previous chapter. To perform a server-side validation, we need to do the following:
- Add Data Annotation attributes to the
ViewModels
model class. The input data is validated against this metadata and the model state is updated automatically. - Update the
view
method to display the validation message for each of the fields. Thespan
tag helper with theasp-validation-for
attribute will be used to display the validation error message. - Update the controller action method to verify the model state. If the model state is valid, we insert the data into the database. Otherwise, the ViewModel is updated and the
view
method is rendered again with the validation error message so that the user can update with valid input data and submit the form again.
Updating ViewModels with the Data Annotation Attribute
The Data Annotation attribute defines the validation rules for the properties of the Model/ViewModel
. If the input data does...