Asp.Net MVC - FluentValidation
Is there a way in Asp.Net MVC to use some kind of fluent validation ?
I means, instead of validation my poco like that :
public class User {
[Required]
public int I开发者_如何转开发d { get; set; }
Having something like that (in an external class) :
User.Validate("Required", "Id");
Is that something possible in Asp.Net MVC 2 (or 3) ?
I know the FluentValidation library exists, but I will like to know if something in the core of Asp.Net MVC allow that.
I don't like to polluted my POCO like that. Also, what happen if I need to validate let say that BeginDate is before EndDate ? With attribute, you can't do that.
FluentValidation integrates pretty well with ASP.NET MVC. It comes with a model binder allowing to automatically apply the validation rules.
So for example:
[Validator(typeof(MyViewModelValidator))]
public class MyViewModel
{
public int? Id { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
}
public class MyViewModelValidator : AbstractValidator<MyViewModel>
{
public MyViewModelValidator()
{
RuleFor(x => x.Id)
.NotNull();
RuleFor(x => x.EndDate)
.GreaterThan(x => x.StartDate);
}
}
and then your controller action:
[HttpPost]
public ActionResult Index(MyViewModel model)
{
if (ModelState.IsValid)
{
// The model is valid => process it
return RedirectToAction("Success");
}
// Validation failed => redisplay the view in order to show error
// messages
return View(model);
}
精彩评论