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.
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));
}
}
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With