DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Data Engineering
  3. Databases
  4. Code First Model Validation With a Fluent API

Code First Model Validation With a Fluent API

See how you can validate your data using a fluent API. Learn step by step how to set up your database and check your inputs against the correct information.

Ahmed Abdi user avatar by
Ahmed Abdi
·
Aug. 30, 16 · Tutorial
Like (5)
Save
Tweet
Share
10.35K Views

Join the DZone community and get the full member experience.

Join For Free

In this article, we are going to learn how to validate types by using fluent validation. We can either do with Data annotation or a fluent API. The simplest way for model validating is by just using data annotation, but if  you want your domains to be clean, then the fluent validation is the preference.

Let's Begin

Step1: Create a new web application and select MVC template, and then Install the entity framework and fluent validation  from nuggets.

Step 2: Next in the model folder, add a 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 a new class, Studentcontext, inside the 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 a folder in the root of the project and add the studentvalidation class. As we can see, our Student validation class inherits AbstractValidator, and this class allows us to define a 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 a connection string in the Web Config file located in the root.

<connectionStrings>
 <add name="stdb" providerName="System.Data.SqlClient" connectionString="Data Source= MMC-PC\SQLEXPRESS;Initial ;Integrated ;" />
 </connectionStrings>


Step 6: Next, add a new controller. In our controller, we are only working with two actions — one for using as input and other for displaying data passed with no validation errors.

namespace MvcModelValidation.Controllers
{
    public class StudentsController : Controller
    {
        private StudentContext db = new StudentContext();
        //Get Students
        public ActionResult Index()
        {
            return View(db.Students.ToList());
        }
        // GET: Students/Create
        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 migrations to prepare the database. Run the following commands in the package manager console, but before that, build the project to check it’s running without errors.

enable-migrations      
add-migration "initial-migration"
update-database -verbose


Step 8: Now we are done, and database is created. Let's fire our application and insert some invalid data.

Image title

Now insert some  valid data

Image title


And there you have it. All done.

API

Published at DZone with permission of Ahmed Abdi. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Automated Performance Testing With ArgoCD and Iter8
  • API Design Patterns Review
  • Spring Cloud: How To Deal With Microservice Configuration (Part 1)
  • TDD: From Katas to Production Code

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: