asp.net MVC5 Verification series of fluent validation_ practical skills

Source: Internet
Author: User

The previous two articles have learned, service-side verification, and client verification, but you have not found that both of these two kinds of authentication have drawbacks, server-side validation, validation logic and the logic of the code mixed together, if the code volume is very large, later maintenance expansion, it is not very convenient. For client authentication, you must enable client-side validation, which is to configure the appropriate node in the configuration file, and to introduce a jquery plug-in. If you disable the JS script on the browser, then the client verification will not work, so here I will continue to learn another validation, that is, fluent Validation.

Fluent validation is an open-source. NET class library that uses the fluent interface and lambda expressions to authenticate entities. Fluent validation is specifically used for verification of entities. The advantage of this is that the validation logic is separated from the business logic of your code. This is the idea of AOP. is crosscutting concerns. You just need to focus on a single module. This guarantees the purity of the code.

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

Example:
Aspect-oriented program are a new software development paradigm that enables modular implementation of Cross-cuttin G Concerns,and poses difficulties for slicing of aspect-oriented programs.
Aspect-oriented programming, as a new type of software development paradigm, can realize the modularity of crosscutting concerns, and its specific language elements and functions are more difficult to slice.
Okay, so much nonsense, just get to the point,
First we create a blank MVC project: Create a new 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;}}}


Then create a new folder validator, add a class inside Customervalidator

Now that you're using fluent Validation, you're referencing its class library.

In the Customervalidator class, inherit the Abstractvalidator abstract class, (PS: This is similar to the fluent API in EF, which inherits the Entitytypeconfiguration class)

Using Fluentvalidation;
Using SERVER_SIDE_VALIDATION_IN_MVC. Models;
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;

Namespace Server_side_validation_in_mvc. Validator
{public
 class customervalidator:abstractvalidator<customer>
 {
  public Customervalidator ()
  {
   rulefor (S => s.name). Notempty (). Withmessage ("Name cannot be empty");
   Rulefor (S => s.email). Notempty (). Withmessage ("e-mail cannot be empty");
   Rulefor (S => s.email). EmailAddress (). Withmessage ("e-mail format is not valid");}}


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}
   );
  

Nothing input, direct click Create:

Enter name, do not enter email

Enter Name,email to enter illegal data

Enter the legitimate data:

This completes the fluent validation verification. As you can see, this kind of verification is clean and concise, configuration information is in a class, easy to maintain and expand. Do not want the data annotation, the validation information and the entity mixed.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.