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.

2
  • Are you doing the check against ModelState.IsValid in your controller action? Commented Jan 16, 2015 at 16:08
  • Yes, but I am trying to do client side validation with it. Commented Jan 16, 2015 at 16:10

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I see, I didn't realize that, though thinking about it now, I should have. Thanks for the info.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.