Code First Model Validation With Fluent API Using ASP.NET MVC

The simplest way for the model validating is just by using data annotation, but if you want your domain to be clean the fluent validation is the best preference.

Let's start now.

Step 1 - Create new Web Application, select MVC template, install entity framework and fluent validation from the nuggets.

Step 2 - In the Model folder, add Student class.

  1. public class Student   
  2. {  
  3.     public int ID {  
  4.         get;  
  5.         set;  
  6.     }  
  7.     public string FirstName {  
  8.         get;  
  9.         set;  
  10.     }  
  11.     public string LastName {  
  12.         get;  
  13.         set;  
  14.     }  
  15.     public string Phone {  
  16.         get;  
  17.         set;  
  18.     }  
  19.     public string Email {  
  20.         get;  
  21.         set;  
  22.     }  
  23. }  
Step 3 - Next, we are to going to create context class, add new class Studentcontext inside DAL folder.
  1. namespace MvcModelValidation.DAL   
  2. {  
  3.     public class StudentContext: DbContext   
  4.     {  
  5.         public StudentContext(): base("stddb")   
  6.         {  
  7.             Database.SetInitializer < StudentContext > (null);  
  8.         }  
  9.         public DbSet < Student > Students   
  10.         {  
  11.             get;  
  12.             set;  
  13.         }  
  14.     }  
  15. }  
Step 4 - Now, create the folder in the root of the project and add studentvalidation class. As we can see, our Student validation class inherits AbstractValidator, this class allows us to define the set of validation rules.
  1. namespace MvcModelValidation.Validations  
  2. {  
  3.     public class StudentValidation: AbstractValidator < Student >   
  4.       {  
  5.         public StudentValidation() {  
  6.             RuleFor(c => c.FirstName).NotEmpty().Length(0, 10);  
  7.             RuleFor(c => c.LastName).NotEmpty().Length(0, 10);  
  8.             RuleFor(c => c.Phone).Length(10).WithMessage("Enter valid number");  
  9.             RuleFor(c => c.Email).EmailAddress();  
  10.         }  
  11.     }  
  12. }  
Step 5 - Add the connection string in Web Config file, located in the root.
  1. <connectionStrings>  
  2.     <add name="stdb" providerName="System.Data.SqlClient" connectionString="Data Source= MMC-PC\SQLEXPRESS;Initial Catalog=stdb;Integrated Security=True;" />   
  3. </connectionStrings>  
Step 6 - Next, add a new controller in your controller. We are only working with the two actions- one for using as an input and other to display the data, passed with no validation errors.
  1. namespace MvcModelValidation.Controllers {  
  2.     public class StudentsController: Controller {  
  3.         private StudentContext db = new StudentContext();  
  4.         //Get Students  
  5.         public ActionResult Index() {  
  6.                 return View(db.Students.ToList());  
  7.             }  
  8.             // GET: Students/Create  
  9.         public ActionResult Create() {  
  10.                 return View();  
  11.             }  
  12.             [HttpPost]  
  13.             [ValidateAntiForgeryToken]  
  14.         public ActionResult Create([Bind(Include = "ID,FirstName,LastName,Phone,Email")] Student student) {  
  15.             StudentValidation val = new StudentValidation();  
  16.             ValidationResult model = val.Validate(student);  
  17.             if (model.IsValid) {  
  18.                 db.Students.Add(student);  
  19.                 db.SaveChanges();  
  20.                 return RedirectToAction("Index");  
  21.             } else {  
  22.                 foreach(ValidationFailure _error in model.Errors) {  
  23.                     ModelState.AddModelError(_error.PropertyName, _error.ErrorMessage);  
  24.                 }  
  25.             }  
  26.             return View(student);  
  27.         }  
  28.     }  
  29. }  
Step 7 - Now, we need to enable the migrations to prepare our database, run the following commands in Package Manager Console, but before you build the project check if it’s running without the errors or not.

enable-migrations
add-migration "initial-migration"
update-database -verbose
 
Step 8 - Now, we are done and our database is created. Let's fire our Application and insert some invalid data.



Now, insert some valid data.

output

 

Ebook Download
View all
Learn
View all