Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FluentValidation allow null OR specify length?

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.

like image 698
BBauer42 Avatar asked Nov 20 '15 15:11

BBauer42


2 Answers

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));
    }
}
like image 169
Yannick Meeus Avatar answered Nov 07 '22 23:11

Yannick Meeus


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");
like image 32
Sagar Nanivadekar Avatar answered Nov 08 '22 01:11

Sagar Nanivadekar