Using Fluentvalidation to validate entities in ASP.

Source: Internet
Author: User

This article reproduced: http://www.cnblogs.com/libingql/p/3801704.html

1, Fluentvalidation Introduction

Fluentvalidation is a data validation component that differs from the ASP. NET Dataannotataion attribute authentication entity, providing a way to validate the separation of entities from validation. The Fluentvalidation also provides a chain-of-expression syntax.

  2, Installation Fluentvalidation

Fluentvalidation Address: http://fluentvalidation.codeplex.com/

Install Fluentvalidation and FLUENTVALIDATION.MVC using the management NuGet package for Visual Studio

  3. Using fluentvalidation verification through modelstate

Project Solution Structure diagram:

  

Entity class Customer.cs:

Using system;using system.collections.generic;using system.linq;using system.web;namespace libing.portal.web.models.entities{public    class Customer    {public        int CustomerID {get; set;}        public string CustomerName {get; set;}        public string Email {get; set;}        public string Address {get; set;}        public string postcode {get; set;}        public float? Discount {get; set;}        public bool Hasdiscount {get; set;}}    }

Data validation class CustomerValidator.cs:

Using system;using system.collections.generic;using system.linq;using system.web;using FluentValidation;using Libing.portal.web.models.entities;namespace libing.portal.web.models.validators{Public    class customervalidator:abstractvalidator<customer>    {public        customervalidator ()        {            rulefor ( Customer = customer. CustomerName). Notnull (). Withmessage ("Customer name cannot be empty");            Rulefor (customer = customer. Email)                . Notempty (). Withmessage ("Mailbox cannot be empty")                . EmailAddress (). Withmessage ("Incorrect mailbox format");            Rulefor (customer = customer. Discount)                . NotEqual (0)                . When (customer = customer. Hasdiscount);            Rulefor (customer = customer. Address)                . Notempty ()                . Withmessage ("Address cannot be empty")                . Length (a)                . Withmessage ("Address length range is 20-50 bytes");}}}    

Controller class CustomerController.cs:

Using system;using system.collections.generic;using system.linq;using system.web;using System.Web.Mvc;using Fluentvalidation.results;using libing.portal.web.models.entities;using Libing.Portal.Web.Models.Validators; Namespace libing.portal.web.controllers{public class Customercontroller:controller {public ActionResult I        Ndex () {return View ();        } public ActionResult Create () {return View ();  } [HttpPost] public actionresult Create (customer customer) {Customervalidator Validator =            New Customervalidator (); Validationresult result = Validator.            Validate (customer); if (!result. IsValid) {result. Errors.tolist (). ForEach (Error = {modelstate.addmodelerror (error). PropertyName, error.                ErrorMessage);            }); } if (Modelstate.isvalid) {return REDIRECTTOACtion ("Index");        } return View (customer); }    }}

View Page create.cshtml, which is automatically generated when you add a view by selecting the Create Template:

@model libing.portal.web.models.entities.customer@{Layout = null;} <! DOCTYPE html>

Operating effect:

  

4, by setting the entity class attribute and validation class to verify

To modify an entity class Customer.cs:

Using system;using system.collections.generic;using system.linq;using system.web;using FluentValidation.Attributes; Using Libing.portal.web.models.validators;namespace libing.portal.web.models.entities{    [Validator (typeof ( Customervalidator)] public    class Customer    {public        int CustomerID {get; set;}        public string CustomerName {get; set;}        public string Email {get; set;}        public string Address {get; set;}        public string postcode {get; set;}        public float? Discount {get; set;}        public bool Hasdiscount {get; set;}}    }

Modify Global.asax.cs:

Using system;using system.collections.generic;using system.linq;using system.web;using System.Web.Mvc;using System.web.routing;using fluentvalidation.attributes;using fluentvalidation.mvc;namespace Libing.Portal.Web{    public class MvcApplication:System.Web.HttpApplication    {        protected void Application_Start ()        {            Arearegistration.registerallareas ();            Routeconfig.registerroutes (routetable.routes);            Fluentvalidation Set            Dataannotationsmodelvalidatorprovider.addimplicitrequiredattributeforvaluetypes = False ;            MODELVALIDATORPROVIDERS.PROVIDERS.ADD (New Fluentvalidationmodelvalidatorprovider (New Attributedvalidatorfactory ( )));        }    }}

Using Fluentvalidation to validate entities in ASP.

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.