18

I have a rule like this:

RuleFor(m => m.Title).Length(1, 75);

However, if the Title is null, I still get the validation stating the Title length must be between 1 and 75 characters, you entered 0.

How can I change the rule so it allows for null title, but if one is specified it must be between 1 and 75 characters? Thanks.

BBauer42
  • 3,549
  • 10
  • 44
  • 81

2 Answers2

37

I'm working on a bit of an assumption here, but I'm guessing your title isn't set to null but to string.Empty. You can add particular clauses to any rule by doing the following:

public class Thing
{
    public string Title { get; set; }
}

public class ThingValidator : AbstractValidator<Thing>
{
    public ThingValidator()
    {
        this.RuleFor(s => s.Title).Length(1, 75).When(s => !string.IsNullOrEmpty(s.Title));
    }
}
Yannick Meeus
  • 5,643
  • 1
  • 35
  • 34
  • 11
    Instead of using `When()` with a negative, you can use `Unless()` with a positive: `.Unless(s => string.IsNullOrEmpty(s.Title))` – Gustaf Liljegren Mar 21 '19 at 16:28
2

As suggested by Yannick Meeus in above post, we need to add 'When' condition to check for not null. It resolved the issue. Here I wanted to allow Phone number to be null, but if specified then it should contain ONLY digits.

RuleFor(x => x.PhoneNumber).Must(IsAllDigits).When(x => !string.IsNullOrEmpty(x.AlternateNumber)).WithMessage("PhoneNumber should contain only digits");