A simple example of the FluentValidation component in asp.net

Source: Internet
Author: User
Tags assert

Here we will introduce a VAB (Validation Application Block), ASP.. net mvc uses the Attribute declarative verification component FluentValidation, which uses the expression syntax chain programming to separate the verification component from the entity. The reason why I like him is that I like expressions and chain.

Enter the topic of today. First, if you do not have this component, you can use NuGet of VS2010 to install it. (if not, install the open source DataBase component: the method mentioned in FluentMigrator ), command:
 

Now we can start to experience it. The entity class do is still the Orders in the previous section:

Public class Orders
   {
Public int ID {get; set ;}

Public string CustomerID {get; set ;}

Public decimal DisCount {get; set ;}

Public DateTime OrderDate {get; set ;}
   }

Verification logic:

Public class OrdersValidator: AbstractValidator <Orders>
    {
Public OrdersValidator ()
        {
RuleFor (orders => orders. CustomerID). NotEmpty (). Length (2, 20). WithName ("CustomerID ");
RuleFor (orders => orders. DisCount). Greaterthanordue to (0). LessThan (1). WithMessage ("discount must between 0 and 1! ");
RuleFor (orders => orders. OrderDate. Date). Greaterthanordue to (DateTime. Now. Date). WithName ("Order Date ");
        }
    }

How do you feel when you see this code? The current language focuses not only on functions but also semantics.

Next we will write a simple test class to test it:

[TestMethod]
Public void TestMethod1 ()
       {
Var orders = new Orders () {DisCount = 2, CustomerID = "1", OrderDate = DateTime. Now. AddDays (-1). Date };
IValidator validator = new OrdersValidator ();
Var results = validator. Validate (orders );

Var validationSucceeded = results. IsValid;
Var failures = results. Errors;
Assert. IsTrue (failures. Any (t => t. PropertyName = "CustomerID "));
Assert. IsTrue (failures. Any (t => t. PropertyName = "DisCount "));
Assert. IsTrue (failures. Any (t => t. PropertyName = "OrderDate. Date "));
Failures. ToList (). ForEach (t => Debug. WriteLine (t. ErrorMessage ));
       }

The unit test results will not be posted, and I feel redundant.

Finally, I forgot to mention that this component provides us with multi-language support in many languages:

Let's look at an example on the official website.

The main source code repository for this project is on GitHub although it is also mirrored to CodePlex.

NuGet packages are available-the package IDs are FluentValidation and FluentValidation. MVC3.

Example

 

The code is as follows: Copy code

Using FluentValidation;

Public class CustomerValidator: AbstractValidator <Customer> {
Public CustomerValidator (){
RuleFor (customer => customer. Surname). NotEmpty ();
RuleFor (customer => customer. Forename). NotEmpty (). WithMessage ("Please specify a first name ");
RuleFor (customer => customer. Company). NotNull ();
RuleFor (customer => customer. Discount). NotEqual (0). When (customer => customer. HasDiscount );
RuleFor (customer => customer. Address). Length (20,250 );
RuleFor (customer => customer. Postcode). Must (BeAValidPostcode). WithMessage ("Please specify a valid postcode ");
  }

Private bool BeAValidPostcode (string postcode ){
// Custom postcode validating logic goes here
  }
}

Customer customer = new Customer ();
CustomerValidator validator = new CustomerValidator ();
ValidationResult results = validator. Validate (customer );

Bool validationSucceeded = results. IsValid;
IList <ValidationFailure> failures = results. Errors;

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.