This is part 17 of Blazor tutorial. In this video we will discuss how do you implement
model validation in an ASP.NET Core REST API. ASP.NET Core provides several built-in
attributes for model validation. Required attribute - this attribute specifies a field
is required. Range attribute specifies the minimum and maximum allowed value.
Minlength specifies the minimum length of a string. MaxLength - maximum length of a
string. Compare - compares two properties of a model, for example compare email and
confirm email properties. Regular expression validates if the provided value matches the
pattern specified by the regular expression. In our solution, the model classes are in this
project "EmployeeManagement.Models". To be able to use the built-in validation attributes we'll
have to bring in a Nuget package. Let's do that using package manager console. First,
select our "EmployeeManagement.Models" project from the drop-down list and
then execute this command "Install-Package System.ComponentModel.Annotations". There we go,
package installation complete. Now, in an ASP.NET Core REST API, to implement model
validation all we have to do is decorate the respective properties of the Employee model
class with the validation attributes that we have just seen. Now, let's make this FirstName
field a required field and to do that all we have to do is decorate this property with the
[Required] attribute. Bring in the namespace System.ComponentModel.DataAnnotations. Let's
also make this LastName property required and while we are here, let's also enforce
min length validation on FirstName. We want to ensure FirstName contains at least a minimum
of two characters. Let's run our project and quickly test model validation using postman.
I have "Postman" up and running. Notice, we are issuing a POST request to our collection URI
"/api/employees" and notice I have deliberately set FirstName property to just one character.
Let's remove this LastName property as well and then send this request to the server. Request
completed. If we take a look at the response we got from the server, notice we got the
HTTP status code 400 Bad Request along with the two validation errors - The last name field is
required the field first name must be a string or array type with a minimum length of 2. Now,
if you don't like these validation error messages you can very easily change them using the error
message property of the respective validation attribute. Now, if it's an asp.net core MVC
web application that you're building then we explicitly check if model state has succeeded
or failed by using ModelState.IsValid property. In an ASP.NET Core Web API project, there is no need
to explicitly check ModelState.IsValid property. Now, if you notice our EmployeesController is
decorated with [ApiController] attribute. So, this attribute takes care of checking if the
model state is valid, if it's not valid it automatically returns the HTTP status code
400 along with the validation errors. Most of our validation requirements can be implemented using
these built-in attributes. However there are few use cases which we cannot implement using
these built-in validation attributes, for example let's say we do not want to allow a new employee
to be created if the provided email is already in use. Let's see how to implement this now. To
be able to check if an employee email address is already in use, I'm going to add a new method to
this interface IEmployeeRepository. It's going to be very similar to this GetEmployee() method. So,
let's make a copy of this and then change the bits that are required. First of all, let's change the
name of the method to GetEmployeeByEmail() and let's pass the employee email as a parameter. Our
obvious next step is to provide implementation for this new interface method. It's going to
be very similar to this GetEmployee() method. So, let's make a copy of this and to get the
signature right, let's copy the name of the method and the parameter from the interface. Instead of
retrieving the employee by employee ID, we now want to retrieve the employee by email. Next,
within our EmployeesController inside this CreateEmployee() method, before we actually
create the new employee, let's check if the provided email is already in use. So, for that,
let's use the injected EmployeeRepository and on this we have GetEmployeeByEmail() method. so let's
retrieve the employee by the provided email. If the variable "emp" is not equal to null that means
the provided email is already in use and we don't want to proceed with the new employee creation,
instead we want to return a validation error, for that all we need to do is,
on the ModelState object call AddModelError() method and then provide values for these two
parameters. I'm going to set the error key to "email" and the error message to - "Employee
email already in use" and then return Bad Request passing it the model state object. With all these
changes in place, let's run our project and quickly test it using postman. Notice,
I've set email to "David@pragimtech.com". This email is already in use. Now, let's try to
create this employee and see what happens. Request completed and if you take a look at the response,
we got the HTTP status code 400 bad request along with the validation error - "Employee
email already in use". That's it in this video. Thank you for listening.