Search code examples
c#fluentvalidation

Fluent Validation check for null OR min max string length


I can't find a question asking for the exact exam problem, so I'm writing my own.

I have to validate a model with several string properties. Each of them could either be Null or between 1 and 100 characters.

I have some other validators where I use this approach:

RuleFor(model => model.Name)
            .Must(name => string.IsNullOrEmpty(name) || name.Length > minLength)
            .WithErrorCode(ErrorCodes.MinStringLength)
            .WithState(model => new
            {
                expected = minLength,
                actual = model.Name.Length
            });

However I also need to check for maxLength, which is basically duplicating the above expression, but check for name.Length < maxLength. Given that I have to validate more than one property this way I feel that some optimization could be done to reduce the amount of code needed for this.

One thing that I started to implement but I couldn't figure out how to make it work is :

RuleFor(model => model.Name)
            .Must(name => string.IsNullOrEmpty(name) || (name.Length > minLength || name.Length < maxLength))
            .WithErrorCode(name.Length <= minLength ? ErrorCodes.MinStringLength : ErrorCodes.MaxStringLength)
            .WithState(model => new
            {
                expected = model.Name <= minLength ? minLength : maxLength,
                actual = model.Name.Length
            });

The problem here is that in .WithErrorCode(.. I don't have acces to name or model. I guess I can assign them to variables outside the RuleFor but I'm not sure for this particular approach.


Solution

  • I think The NotEmpty and the Length validator is what you are wanting

    RuleFor(customer => customer.Surname).NotEmpty().Length(1, 250);

    .NotEmpty() means cannot be null or empty

    .Length(1, 250); //must be between 1 and 250 chars (inclusive)