0

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.

JB06
  • 1,881
  • 14
  • 28

1 Answers1

1

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.

Community
  • 1
  • 1
Matthew Jones
  • 25,644
  • 17
  • 102
  • 155
  • I see, I didn't realize that, though thinking about it now, I should have. Thanks for the info. – JB06 Jan 16 '15 at 16:22