ismail baig
ismail baig

Reputation: 891

Conditional FluentValidation in mvc 4 application

My Model is as below

[Validator(typeof(PersonValidator))]
public class Person
{
    public string Id { get; set; }
    public string Name { get; set; }

}

public class PersonValidator : AbstractValidator<Person>
{
    public PersonValidator()
    {

      RuleFor(x => x.Name).Length(4, 10)
        .When(per => per.Id.ToUpper() == "FOO");
    }
}

My controller is as below

 public class HomeController : Controller
{
    [HttpPost]
    public ActionResult PersonAction(Person p)
    {

        if (ModelState.IsValid)
        {
            return View();
        }
        else
        {
            return View();
        }
    }
}

i want the following validation been set using Fluent Validation

  1. If Id == 'foo',then Name should have its Length validation
  2. If Id !== 'foo',then Name should NOT have Length validation

But Lenght validation seems to be always getting applied. i.e. irrespective of what is the value of Id, What am i missing ?

Upvotes: 0

Views: 351

Answers (1)

Tarek
Tarek

Reputation: 1279

When(x => string.Equals(x.Id, "foo", System.StringComparison.CurrentCultureIgnoreCase), () => 
{
   RuleFor(x => x.Name).Length(4, 10).WithMessage([YOUR MESSAGE]);
});

Upvotes: 1

Related Questions