0
votes

I am having an issue with FluentValidation's Must method. I have this rule in my view model:

RuleFor(v => v.StateCd).Must(stateCd => BeAValidStateCode(stateCd)).WithMessage("Please enter a valid, 2 character state code.")
                                            .NotEmpty().WithMessage("State is required.")
                                            .Length(2).WithMessage("State should be 2 characters.");

The validation method is in the view model:

private bool BeAValidStateCode(string stateCode)
{
    string states = "|AL|AK|AS|AZ|AR|CA|CO|CT|DE|DC|FM|FL|GA|GU|HI|ID|IL|IN|IA|KS|KY|LA|ME|MH|MD|MA|MI|MN|MS|MO|MT|NE|NV|NH|NJ|NM|NY|NC|ND|MP|OH|OK|OR|PW|PA|PR|RI|SC|SD|TN|TX|UT|VT|VI|VA|WA|WV|WI|WY|";

    return stateCode.Length == 2 && states.IndexOf("|" + stateCode + "|") >= 0;
}

I want to ensure that the state code the user enters is two characters and is contained in this string. I have tested the validation method and know that it works, but it validates input such as "aa", "jj", etc. Am I using the Must rule incorrectly?

Any help is appreciated.

UPDATE: Since posting this I have tried several other things, including just having the BeAValidStateCode method return false, and it still validates anything I put in.

1
Are you doing the check against ModelState.IsValid in your controller action? - Matthew Jones
Yes, but I am trying to do client side validation with it. - JB06

1 Answers

1
votes

FluentValidation doesn't do client-side validation for rules like Must() without implementing a custom client-side provider.

Generally speaking, you should always have server-side validation, with client-side being a welcome option (because the user can always disable Javascript).

If you want to build a custom validation provider, you can maybe get some idea from this answer or maybe this blog post.