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 ?

7
  • what you have done so far? any error? Commented May 13, 2016 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 Commented May 13, 2016 at 17:06
  • the same thing is done Here .go through this link Commented May 13, 2016 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. Commented May 13, 2016 at 17:31
  • You can use When() method in your validator Commented May 13, 2016 at 18:11

1 Answer 1

1
When(x => string.Equals(x.Id, "foo", System.StringComparison.CurrentCultureIgnoreCase), () => 
{
   RuleFor(x => x.Name).Length(4, 10).WithMessage([YOUR MESSAGE]);
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.