How to Use fluent validation for nullable string?

3.1k Views Asked by At

I have the below code which is throwing an exception for null check:

 RuleFor(x => x.TestString)
                .Must(x => !string.IsNullOrEmpty(x))
                .When(y => y.OtherArray!= null && y.OtherArray.Count > 0)
                .WithMessage("required") 
                .Must(x=> x.TestString.Equals("tiktok"))
                .WithMessage("Invalid") 

but the above code is throwing Object null reference exception when TestString is null.

My requirement is when "OtherArray" has a value, then "TestString" must be equal to "tiktok" when an invalid TestString Invalid error message should be shown.

When "OtherArray" is null or empty then no need to check the "TestString". Can anyone please help?

1

There are 1 best solutions below

0
gidanmx2 On BEST ANSWER

Try this:

RuleFor(x => x.TestString)
            .Must(x => !string.IsNullOrEmpty(x))
            .When(y => y.OtherArray!= null && y.OtherArray.Count > 0)
            .WithMessage("required") 
            .Must(x=> x.TestString != null && x.TestString.Equals("tiktok"))
            .WithMessage("Invalid")