1

This is my code:

RuleFor(x => x.Content).NotEmpty().Must(content => content.Trim().Length > 0);

I expect it should behave as

if (NotEmpty(x.Content) && x.Content.Trim().Length > 0)

statement but it throws NullReferenceException if x.Content is null.

Please help me with a workaround.

SKINDER
  • 950
  • 3
  • 17
  • 39

3 Answers3

2

There is Unless which allows you to execute a rule based on a condition. You need to split up your rule into two, however:

RuleFor(x => x.Content).NotEmpty();
RuleFor(x => x.Content).Must(content => content.Trim().Length > 0).Unless(x => x == null);

Or you could use the ?? operator, which is even more compact:

RuleFor(x => (x.Content ?? "").Trim()).NotEmpty();
Matthias Meid
  • 12,455
  • 7
  • 45
  • 79
2

It seems this code works perfectly too:

RuleFor(x => x.Content)   
    .Cascade(CascadeMode.StopOnFirstFailure)    
        .NotEmpty()   
        .Must(content => content.Trim().Length > 0);
SKINDER
  • 950
  • 3
  • 17
  • 39
1

You could write a custom rule. If the rule returns true, then create a ValidationFailure. Something like this:

public class ViewModelValidator : AbstractValidator<ViewModel>
{
    public ViewModelValidator()
    {
        Custom(r => ContentIsEmpty(r) ? new ValidationFailure("Content", "Content must not be empty.") : null);
    }

    private static bool ContentIsEmpty(ViewModel viewModel)
    {
        return string.IsNullOrWhiteSpace(viewModel.Content);
    }
}
levelnis
  • 7,665
  • 6
  • 37
  • 61