Fluent Validation and mvc5fluent in ASP. NET MVC5 Verification Series

Source: Internet
Author: User

Fluent Validation and mvc5fluent in ASP. NET MVC5 Verification Series

The previous two articles learned about server-side verification and client-side verification. But have you found that both of these two verification methods have drawbacks? server-side verification, the verification logic is mixed with the code logic. If the code volume is large, it is not convenient to extend the maintenance in the future. To verify the client, you must enable client authentication, that is, configure the corresponding node in the configuration file, and introduce the Jquery plug-in. If the js script is disabled manually in the browser, the client authentication does not work, so here, I will continue to learn another verification, that is, Fluent Validation.

Fluent Validation is an open-source. NET class library that uses Fluent interfaces and lambda expressions to verify entities. Fluent Validation is used for entity verification. It has the following advantages: it opens the authentication logic and the business logic of your code separately. This is the idea of AOP. Is the cross-cutting concern. You only need to pay attention to a module. This ensures the purity of the Code.

Fluent Validation Open Source Address: https://github.com/JeremySkinner/fluentvalidation

Example:
Aspect-oriented program is a new software development paradigm that enables modular implementation of cross-cutting concerns, and poses difficulties for slicing of aspect-oriented programs.
As a new software development model, Aspect-Oriented Programming can implement modularization of cross-cutting concerns. Its unique language elements and functions increase the difficulty of slicing.
Okay, too much nonsense. Go to the topic,
First, create a blank MVC project: Create a class Customer under the Model Folder:

using System;using System.Collections.Generic;using System.Linq;using System.Web;namespace Server_Side_Validation_IN_MVC.Models{ public class Customer {  public string Name { get; set; }  public string Email { get; set; } }}

Create a new folder Validator and add a class CustomerValidator to it.

Since it is necessary to use Fluent Validation, it is necessary to reference its class library.

In the CustomerValidator class, inherit the AbstractValidator abstract class (PS: similar to the Fluent API in EF, And the EntityTypeConfiguration class in EF)

Using FluentValidation; using Server_Side_Validation_IN_MVC.Models; using System. collections. generic; using System. linq; using System. web; namespace Server_Side_Validation_IN_MVC.Validator {public class CustomerValidator: AbstractValidator <Customer> {public mermervalidator () {RuleFor (s => s. name ). notEmpty (). withMessage ("name cannot be blank"); RuleFor (s => s. email ). notEmpty (). withMessage ("email cannot be blank"); RuleFor (s => s. email ). emailAddress (). withMessage ("invalid email format ");}}}

Code in the controller:

using FluentValidation.Results;using Server_Side_Validation_IN_MVC.Models;using Server_Side_Validation_IN_MVC.Validator;using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;namespace Server_Side_Validation_IN_MVC.Controllers{ public class CustomerController : Controller {  // GET: Customer  public ActionResult Index()  {   return View();  }  [HttpPost]  public ActionResult Index(Customer model)  {   CustomerValidator validator = new CustomerValidator();   ValidationResult result = validator.Validate(model);   if (result.IsValid)   {    ViewBag.Name = model.Name;    ViewBag.Email = model.Email;   }   else   {    foreach (var item in result.Errors)    {     ModelState.AddModelError(item.PropertyName, item.ErrorMessage);    }   }   return View(model);  } }}
 

Modify the default route:

public static void RegisterRoutes(RouteCollection routes)  {   routes.IgnoreRoute("{resource}.axd/{*pathInfo}");   routes.MapRoute(    name: "Default",    url: "{controller}/{action}/{id}",    defaults: new { controller = "Customer", action = "Index", id = UrlParameter.Optional }   );  }

If you do not enter anything, click Create:

Enter Name without Email

Enter Name or Email to enter invalid data

Enter valid data:

The Fluent Validation is completed here. As you can see, this verification is much more clean and concise, and the configuration information is in a class to facilitate maintenance and expansion. Instead of mixing the verification information with the entity as the data annotation.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.