Paul
Paul

Reputation: 225

Jquery Validator - check input against a list of accepted values

I would normally just do this with a drop down list but the client has requested that it be a text input...

Basically, I'd like to use Jquery validator to check that a user has entered 1 of 50 valid US state abbreviations into a text input box. If not, they'll get an error. I can't seem to find a function that does this. Any help is greatly appreciated!

Upvotes: 12

Views: 8517

Answers (3)

mcgrailm
mcgrailm

Reputation: 17640

Here's a validation method you can add for use with jquery validate

First you declare a validator:

jQuery.validator.addMethod("isstate", function(value) {
    var states = [
        "AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DE", "FL", "GA",
        "HI", "ID", "IL", "IN", "IA", "KS", "KY", "LA", "ME", "MD",
        "MA", "MI", "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ",
        "NM", "NY", "NC", "ND", "OH", "OK", "OR", "PA", "RI", "SC",
        "SD", "TN", "TX", "UT", "VT", "VA", "WA", "WV", "WI", "WY",
        "AS", "DC", "FM", "GU", "MH", "MP", "PR", "PW", "VI"
    ];
    return $.inArray(value.toUpperCase(), states) != -1;
}, "Data provided is not a valid state");

Then apply the validator

$("#myform").validate()

and in your form you want to add the class to the form element to check

<input type="text" value="de" class="isstate" />

Here's a working demo

Upvotes: 19

Naveed Ahmad
Naveed Ahmad

Reputation: 3175

Here is a dirty quick solution:

http://jsfiddle.net/naveed_ahmad/CqXZu/1/

Upvotes: 0

chris polzer
chris polzer

Reputation: 3367

You could use a change() listener that simply checks the input against your list of valid input strings and only enable submit buttons if you have a match.

Anyways. For user experience, it is better to show a dropdown selector list of all the possible states. At least that is what I thought first, when I reaad your question.

Regards,

Chris

Upvotes: 1

Related Questions