jQuery验证程序-根据接受值列表检查输入 [英] 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...
基本上,我想使用Jquery验证程序检查用户是否已在文本输入框中输入50个有效的美国州缩写中的1个。如果没有,他们会得到一个错误。我似乎找不到执行此操作的函数。
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!
推荐答案
在这里,您可以添加验证方法以供 jquery validate
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");
然后应用验证器
$("#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" />
这里是工作演示
这篇关于jQuery验证程序-根据接受值列表检查输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!