The FluentValidation configured for use with ASP.NET MVC 5 project

1. Install nuget of mvc project    Install-Package FluentValidation.Mvc5

Configuring validator

protected void Application_Start() {
    AreaRegistration.RegisterAllAreas();

    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);

    FluentValidationModelValidatorProvider.Configure();
}

 

3. Add the test validator

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

 

 

        public ActionResult Create([CustomizeValidator(RuleSet = "MyRuleset")] Person person)
        {
            if (!ModelState.IsValid)
            { // re-render the view when validation failed.

                return View("Create", person);
            }

            TempData["notice"] = "Person successfully created";
            return RedirectToAction("Index");

        }

You can also specify a set of rules at the time of verification

Guess you like

Origin www.cnblogs.com/student-note/p/11779815.html