Package Introduction-Fluent Validation (for verification)

Source: Internet
Author: User

Install-package fluentvalidation

If you use MVC5 you can use the following package

Install-package FLUENTVALIDATION.MVC5

Example:

public class Customervalidator:abstractvalidator<customer> {public Customervalidator () { Cannot be an empty rulefor (Customer = customer. Surname).                        Notempty (); Custom Prompt rulefor (customer = customer. forename). Notempty ().            Withmessage ("Pls Specify a First name"); Conditional judgment rulefor (customer = customer. Discount). NotEqual (0). When (customer = customer.            Hasdiscount); The limit of the string length is rulefor (customer = customer. Address).            Length (20, 250); Use the Custom validator rulefor (customer = customer. Postcode). Must (Beavalidpostcode).        Withmessage ("Pls Specify a valid postcode"); }///<summary>//custom validation///</summary>//<param name= "Arg" ></param&gt        ; <returns></returns> private bool Beavalidpostcode (string arg) {throw new Notimpl        Ementedexception (); }    }
Customer customer = new Customer (); Customervalidator validator = new Customervalidator (); Validationresult results = validator. Validate (customer); bool validationsucceeded = results. isvalid;ilist<validationfailure> failures = results. Errors;

  

Apply chained validation on an attribute

public class Customervalidator:abstractvalidator<customer> {public  customervalidator {    rulefor ( Customer = customer. Surname). Notnull (). NotEqual ("foo");}  }

Throw exceptions

Customer customer = new Customer (); Customervalidator validator = new Customervalidator (); validator. Validateandthrow (customer);

Using validation in complex attributes

public class Customer {public  string Name {get; set;}  Public address address {get; set;}} public class Address {public  string Line1 {get; set;}  public string Line2 {get; set;}  public string Town {get; set;}  public string County {get; set;}  public string postcode {get; set;}}

public class Addressvalidator:abstractvalidator<address> {public  addressvalidator () {    rulefor ( Address = address. Postcode). Notnull ();    Etc  }}

public class Customervalidator:abstractvalidator<customer> {public  customervalidator () {    rulefor ( Customer = customer. Name). Notnull ();    Rulefor (customer = customer. Address). Setvalidator (New Addressvalidator ())  

Using Validator in Collection properties

public class Ordervalidator:abstractvalidator<order> {public    ordervalidator () {        rulefor (x = x). ProductName). Notnull ();        Rulefor (x = x.cost). GreaterThan (0);}    }

public class Customervalidator:abstractvalidator<customer> {public    customervalidator () {        rulefor (x = > X.orders). Setcollectionvalidator (New Ordervalidator ());}    } var validator = new Customervalidator (); var results = validator. Validate (customer);

The error message for the collection validation is as follows

foreach (var result in results. Errors) {   Console.WriteLine ("Property Name:" + result.) PropertyName);   Console.WriteLine ("Error:" + result.) errormessage);   Console.WriteLine ("");}

Property Name:orders[0]. Costerror: ' Cost ' must is greater than ' 0 '. Property Name:orders[1]. Productnameerror: ' Product Name ' must not is empty.

Validating collections

RuleSet allows you to selectively verify that some validation groups ignore certain validation groups

public class Personvalidator:abstractvalidator<person> {public  personvalidator () {     RuleSet ("Names", ( ) = = {        rulefor (x = x.surname). Notnull ();        Rulefor (x = x.forename). Notnull ();     });      Rulefor (x = x.id). NotEqual (0);}  }

The following code we only verify the surname and forename two properties of the person

var validator = new Personvalidator (); var person = new person (); var result = validator. Validate (person, RuleSet: "Names");

Validate multiple collections at once

Validator. Validate (person, RuleSet: "Names,myruleset,someotherruleset")

Also you can verify the rules that are not included in the ruleset these validations are a special ruleset named "Default"

Validator. Validate (person, RuleSet: "Default,myruleset")

Regular Expression Validator

Rulefor (customer = customer. Surname). Matches ("Some regex here");

Email Authenticator

Rulefor (customer = customer. Email). EmailAddress ();

Overriding the default property name

Rulefor (customer = customer. Surname). Notnull (). Withname ("Last Name");

Or

public class Person {  [Display (name= ' last Name ')] public  string Surname {get; set;}}

Setting validation Criteria

When (customer = customer. Ispreferred, () = {   Rulefor (customer = customer. Customerdiscount). GreaterThan (0);   Rulefor (customer = customer. Creditcardnumber). Notnull ();});

Write a custom property validator

public class Listmustcontainfewerthantenitemsvalidator<t>: propertyvalidator {public Listmustcontainfewerthantenitemsvalidator (): Base ("Property {propertyname} contains more than items!") {}protected override bool IsValid (Propertyvalidatorcontext context) {var list = context. PropertyValue as ilist<t>;if (list! = null && list. Count >=) {return false;} return true;}}

public class Personvalidator:abstractvalidator<person> {public    personvalidator () {       rulefor (person = > Person. Pets). Setvalidator (New listmustcontainfewerthantenitemsvalidator<pet> ());}    }

Integration with MVC

1.

protected void Application_Start () {    arearegistration.registerallareas ();    Registerglobalfilters (globalfilters.filters);    RegisterRoutes (routetable.routes);    Fluentvalidationmodelvalidatorprovider.configure ();}

2.

[Validator (typeof (Personvalidator))]public class Person {public int Id {get; set;} public string Name {get; set;} public string Email {get; set;} public int Age {get; set;}} public class Personvalidator:abstractvalidator<person> {public Personvalidator () {rulefor (x = x.id). Notnull (); Rulefor (x = x.name). Length (0, 10); Rulefor (x = x.email). EmailAddress (); Rulefor (x = x.age). Inclusivebetween (18, 60);}}

3.

[Httppost]public actionresult Create (person person) {if (! Modelstate.isvalid) {//Re-render the view when validation Failed.return view ("Create", person);} tempdata["notice"] = "person successfully created"; return redirecttoaction ("Index"); }

Or verify only the specified ruleset

Public ActionResult Save ([Customizevalidator (ruleset= "Myruleset")] Customer Cust) {  //...}

Or only the specified property is validated

Public ActionResult Save ([Customizevalidator (properties= "Surname,forename")] Customer Cust) {  //...}

In addition, there is a hook in the authentication permission to do some work by implementing Ivalidatorinterceptor in the front and back of the validation

Public interface Ivalidatorinterceptor {    validationcontext beforemvcvalidation (controllercontext ControllerContext, Validationcontext validationcontext);     Validationresult aftermvcvalidation (ControllerContext controllercontext, Validationcontext ValidationContext, Validationresult result);}

  

Package Introduction-Fluent Validation (for verification)

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.