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.
- public class Student
- {
- public int ID {
- get;
- set;
- }
- public string FirstName {
- get;
- set;
- }
- public string LastName {
- get;
- set;
- }
- public string Phone {
- get;
- set;
- }
- public string Email {
- get;
- set;
- }
- }
Step 3 - Next, we are to going to create context class, add new class Studentcontext inside DAL folder.
- namespace MvcModelValidation.DAL
- {
- public class StudentContext: DbContext
- {
- public StudentContext(): base("stddb")
- {
- Database.SetInitializer < StudentContext > (null);
- }
- public DbSet < Student > Students
- {
- get;
- set;
- }
- }
- }
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.
- namespace MvcModelValidation.Validations
- {
- public class StudentValidation: AbstractValidator < Student >
- {
- public StudentValidation() {
- RuleFor(c => c.FirstName).NotEmpty().Length(0, 10);
- RuleFor(c => c.LastName).NotEmpty().Length(0, 10);
- RuleFor(c => c.Phone).Length(10).WithMessage("Enter valid number");
- RuleFor(c => c.Email).EmailAddress();
- }
- }
- }
Step 5 - Add the connection string in Web Config file, located in the root.
- <connectionStrings>
- <add name="stdb" providerName="System.Data.SqlClient" connectionString="Data Source= MMC-PC\SQLEXPRESS;Initial Catalog=stdb;Integrated Security=True;" />
- </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.
- namespace MvcModelValidation.Controllers {
- public class StudentsController: Controller {
- private StudentContext db = new StudentContext();
-
- public ActionResult Index() {
- return View(db.Students.ToList());
- }
-
- public ActionResult Create() {
- return View();
- }
- [HttpPost]
- [ValidateAntiForgeryToken]
- public ActionResult Create([Bind(Include = "ID,FirstName,LastName,Phone,Email")] Student student) {
- StudentValidation val = new StudentValidation();
- ValidationResult model = val.Validate(student);
- if (model.IsValid) {
- db.Students.Add(student);
- db.SaveChanges();
- return RedirectToAction("Index");
- } else {
- foreach(ValidationFailure _error in model.Errors) {
- ModelState.AddModelError(_error.PropertyName, _error.ErrorMessage);
- }
- }
- return View(student);
- }
- }
- }
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.