0

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 ?

ismail baig
  • 861
  • 2
  • 11
  • 39
  • what you have done so far? any error? – Usman lqbal May 13 '16 at 17:05
  • i tried but am not able to basically get any correct approch as am very new to Fluent validation. Infact today is the first time i have heard of it and am implementing it in my application – ismail baig May 13 '16 at 17:06
  • the same thing is done [Here](http://stackoverflow.com/a/8086267/4154016) .go through this link – Usman lqbal May 13 '16 at 17:21
  • i did check this before writing a question as i could not make out how to implement. It would be great if you could post a sample code. – ismail baig May 13 '16 at 17:31
  • You can use When() method in your validator – David Levin May 13 '16 at 18:11
  • @EvgenyLevin: I tried with "When" ( and have edited the question with what is tried), but still it seems to be not working. Could you please take a look at the approach i did (it's in the question itself now). – ismail baig May 15 '16 at 05:18
  • @ismailbaig your example is exact as answer I planned to post. I have no concrete answer, but try to replace length validation with custom validation using Must() method and try to watch at your model in Debug mode. It can help to figure out what is the problem. – David Levin May 15 '16 at 18:25

1 Answers1

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