استفاده از FluentValidation در ASP.NET MVC
نویسنده: میثم مجیدی
تاریخ: ۱۳۹۱/۰۸/۲۰ ۱۶:۵
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
protected void Application_Start() {
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
FluentValidationModelValidatorProvider.Configure();
}
[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 class PeopleController : Controller {
public ActionResult Create() {
return View();
}
[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");
}
}
@Html.ValidationSummary()
@using (Html.BeginForm()) {
Id: @Html.TextBoxFor(x => x.Id) @Html.ValidationMessageFor(x => x.Id)
<br />
Name: @Html.TextBoxFor(x => x.Name) @Html.ValidationMessageFor(x => x.Name)
<br />
Email: @Html.TextBoxFor(x => x.Email) @Html.ValidationMessageFor(x => x.Email)
<br />
Age: @Html.TextBoxFor(x => x.Age) @Html.ValidationMessageFor(x => x.Age)
<input type="submit" value="submit" />
}
public ActionResult Save([CustomizeValidator(RuleSet="MyRuleset")] Customer cust) {
// ...
}
public interface IValidatorFactory {
IValidator<T> GetValidator<T>();
IValidator GetValidator(Type type);
}
ObjectFactory.Configure(cfg => cfg.AddRegistry(new MyRegistry()));
public class MyRegistry : Registry {
public MyRegistry() {
For<IValidator<Person>>()
.Singleton()
.Use<PersonValidator>();
}
}
public class MyRegistry : Registry {
public MyRegistry() {
AssemblyScanner.FindValidatorsInAssemblyContaining<MyValidator>()
.ForEach(result => {
For(result.InterfaceType)
.Singleton()
.Use(result.ValidatorType);
});
}
}
protected void Application_Start() {
RegisterRoutes(RouteTable.Routes);
//Configure structuremap
ObjectFactory.Configure(cfg => cfg.AddRegistry(new MyRegistry()));
ControllerBuilder.Current.SetControllerFactory(new StructureMapControllerFactory());
//Configure FV to use StructureMap
var factory = new StructureMapValidatorFactory();
//Tell MVC to use FV for validation
ModelValidatorProviders.Providers.Add(new FluentValidationModelValidatorProvider(factory));
DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
}
public class StructureMapValidatorFactory : ValidatorFactoryBase {
public override IValidator CreateInstance(Type validatorType) {
return ObjectFactory.TryGetInstance(validatorType) as IValidator;
}
}