-1

I have never heard of FluentValidation until today while I was working on a project, so I have run into an issue. I have this..

RuleFor(x=>x.Company)
    .NotEmpty()
    .WithMessage("Company Required");
RuleFor(x => x.FirstName)
    .NotEmpty()
    .WithMessage(FirstName Required");
RuleFor(x => x.LastName)
    .NotEmpty()
    .WithMessage("LastName Required");

and a bunch of other RuleFor statements.What I need to do is..

If Company field is empty then require validation for FirstName and LastName, but if Company field is not empty then don't apply validation to FirstName and LastName

I have no idea where to start.

EDIT

I tried the When condition and came up with this

When(x => x.Company == "" || x.Company == null, () =>
  {
     RuleFor(x => x.FirstName)
    .NotEmpty()
    .WithMessage("FirstName Required");

    RuleFor(x => x.LastName)
    .NotEmpty()
    .WithMessage("LastName Required");
  });

and I "think" that should have set off the validation for FirstName and LastName, but it didn't.

Then I tried this way

When(x.Company.length == 0, () =>
  {
     RuleFor(x => x.FirstName)
    .NotEmpty()
    .WithMessage("FirstName Required");

    RuleFor(x => x.LastName)
    .NotEmpty()
    .WithMessage("LastName Required");
  });

and the same thing happened, the FirstName and LastName validation didn't happen.

Chris
  • 2,953
  • 10
  • 48
  • 118
  • 1
    [Specifying a condition with When/Unless](https://github.com/JeremySkinner/FluentValidation/wiki/d.-Configuring-a-Validator#user-content-specifying-a-condition-with-whenunless) – jmoerdyk Feb 17 '17 at 21:42
  • @jmoerdyk, I am looking at that right now – Chris Feb 17 '17 at 21:42
  • my confusion is laying in the when because the examples are showing how it would work with a bool and not a string – Chris Feb 17 '17 at 21:52
  • So you do a test on the string that results in a boolean. [String.IsNullOrEmpty()](https://msdn.microsoft.com/en-us/library/system.string.isnullorempty(v=vs.110).aspx), `String.Length == 0`, etc. – jmoerdyk Feb 17 '17 at 22:01

1 Answers1

1

Your first attempt at using the When statement should have worked. This is what worked for me.

When(x => string.IsNullOrWhiteSpace(x.Company), () => {
    RuleFor(x => x.FirstName)
        .NotEmpty()
        .WithMessage("{PropertyName} Required");

    RuleFor(x => x.LastName)
        .NotEmpty()
        .WithMessage("{PropertyName} Required");
});
Stout01
  • 1,116
  • 1
  • 10
  • 20