【发布时间】:2011-02-17 22:20:09
【问题描述】:
我假设我在这里需要一个正则表达式?
我有一个邮政编码字段,并且邮政编码必须在芝加哥市区范围内。幸运的是所有邮政编码都以 606 开头。所以我需要轮询输入以确保输入的邮政编码是 5 位数字并以数字 606 开头:
我的输入足够基本:
<label for="dzip"><span class="red">♥ </span>Zip:</label>
<input name="attributes[address_zip]" id="dzip" type="text" size="30" class="required zip-code" />
然后我的城市脚本就很简单了。我也只需要将其应用于邮政编码:
jQuery.validator.addMethod("Chicago", function(value) {
return value == "Chicago";
}, '**Recipient must reside in Chicago City Limits**');
如果我展示了电话号码插件的功能(美国),可能会有所帮助。基本上我需要把它翻译成拉链:
jQuery.validator.addMethod("phoneUS", function(phone_number, element) {
phone_number = phone_number.replace(/\s+/g, "");
return this.optional(element) || phone_number.length > 9 && phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
}, "Please specify a valid phone number");
这部分的作用/意思是什么?:
phone_number.replace(/\s+/g, "")
我直接从验证网站上的示例中放入了电话部分。
所有伟大(和快速)输入的最终答案是这样的:
jQuery.validator.addMethod("zip-code", function(zip_code, element) {
zip_code = zip_code.replace(/\s+/g, "");
return this.optional(element) || zip_code.length == 5 && zip_code.match(^606[0-9]{2}$);
}, "Please specify a City of Chicago Zip Code");
【问题讨论】:
-
从内存中
phone_number.replace(/\s+/g, "")删除所有空格字符。 -
顺便说一句,杰米,因为正则表达式你不需要 .length == 5 因为如果它不是 5 位数字,正则表达式就会失败。
标签: jquery jquery-validate validation