Validating Models in a Controller
Validation involves both model and controller components of an MVC application. After we have defined validation rules using attributes on the model, we must also update the controller to ensure that the rules are checked and appropriate action is taken when validation fails.
Before diving into the details of the code, let’s consider the logical flow of control for validating data in a request. Let’s check out our
POST action method for processing the Add Event form. Remember that this method uses model binding to create new
AddEventViewModel objects from form submissions.
The flow of this request can be described as follows:
- Server receives
- Server creates
newEventobject using request parameters
Add()is called with
- A redirect response is returned, redirecting the user to
The request creates an
Event object using data from the incoming request. Regardless of what the data looks like, the new object is saved to the data layer. The user could submit an empty form, with no name or description filled in, and our code would be happy to create an
Event and save it. Similarly, a user could submit the full text of the any novel as the description. This isn’t great.
Technically, submitting a request containing a full length novel would fail with most applications. This is because web servers typically set a limit on the maximum size of a
POST request. However, our application code is willing to take requests of any size, at this point.
Now that we have added validation attributes to the ViewModel, we want to refactor our controller to and handle errors in form submission. Our modest validation rules for a new
AddEventViewModel object are as follows:
Nameproperty must contain between 3 and 50 characters,
Descriptionproperty may contain no more than 500 characters, and
ContactEmailproperty must satisfy email formatting rules.
With these rules in place, conceptually, the flow of our controller code should look more like the following:
addEventViewModelobject using request parameters
POSTrequest type) is called with
Controller checks for validation errors in the ViewModel object. If errors are found, return the user to the form. Otherwise, proceed.
addEventViewModelis used to create a new
newEvent, which is saved to the data store.
A redirect response is returned, redirecting the user to
Let’s look at how we can practically do this within ASP.NET Core MVC.
Handling Validation Errors
When using model binding, we can use tools to validate new model objects before they are saved to a data layer or database.
Add() action method uses model binding to receive an
AddEventViewModel object when the form is posted.
That ViewModel instance is created using form data. This object is NOT validated automatically, even if validation attributes are present on its fields.
Recall that both the model and controller play a role in validation. The model’s responsibility is simply to define validation rules. The controller must check that those rules are satisfied.
ModelState.IsValid will check if the constraints on the model properties are met.
If these constraints are met,
ModelState.IsValid equates to true and we want to create and add an Event object to our list of events.
If these constraints are not met and the ViewModel object is not valid, we want to redirect the user back to the Add Event form.
One of the constraints that
ModelState.IsValid checks for is nullability. If a value is
null, it will not pass this check. This is why we declared the members of the
Event model and
AddEventViewModel ViewModel as nullable with the
? then the controller considers this
false and will not update the form.
Once we are done refactoring the
Add() action method to use
ModelState.IsValid, our action method will look like the code below.
Now we have refactored our action method to handle any errors in form submission. However, if you submit a value that doesn’t meet our conditions, you won’t see any error messages indicating what was wrong with your submission. Let’s tackle that next!
Check Your Understanding
Which of the following statements about
ModelState.IsValid are true?
ModelState.IsValidcan only be used in conjunction with model binding.
ModelState.IsValidmeans that a method will never be called with invalid data.
- ASP.NET can infer validation requirements based on the name of a field.