views:

52

answers:

1

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 Id { 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.

+4  A: 

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);
}
Darin Dimitrov
But I think the client side validation is not perfect ?
Melursus
No, it's not prefect but it works with simple rules like `NotNull`. For custom functions you need to write custom client side validation.
Darin Dimitrov