邮编验证,显示特定状态的错误 [英] Zipcode validation that shows an error for particular states

查看:114
本文介绍了邮编验证,显示特定状态的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一种表单,当人们插入特定的邮政编码或邮政编码范围时,会弹出一个错误消息.

I'm trying to create a form that pops-up an error when people insert a specific zip code or range of zip codes.

例如:

如果潜在的潜在客户填写表格并输入华盛顿州的邮政编码,那么我会希望弹出一个错误消息,说我们不提供该州的产品.

If a potential lead fills out a form and enters a Washington state zip code I'd then want an error to pop-up to say we don't offer the product in that state.

我已经搜索过Google和Stackoverflow,但仍未找到有效的代码示例...我看到了类似的示例,但与我的示例所说的不完全相同.

I've search Google and Stackoverflow but still haven't found a working example of code... I've seen ones that are similar but not exactly what my example says.

我要查找的示例可能在javascript或jquery中

the example I'm looking for could be in javascript or jquery

推荐答案

考虑ID为zipCode的输入元素

Considering an input element with the ID of zipCode

<input id="zipCode" name="zipCode" />

我们可以通过做类似的事情来捕捉它的价值

We can capture the value of it by doing something like

var zipCode = $("#zipCode").val();

考虑构建类似...的数组

Considering an array built like...

var acceptableZipCodes = ["53782", "11709", "97035", "86531"]; 

我们可以测试一下zipCode的值是否在数组中,如果不是,我们将返回警报.

We can test to see if the value of zipCode is within the array, if it's not, we'll return an alert.

if($.inArray(zipCode, acceptableZipCodes)){
  //do nothing, or do whatever you want
  //we have a return true here.
}else{
  alert("Sorry. we don't offer products in that state.");
}

现在,我们可能应该将代码放入事件中.让我们使用keyup函数,但是由于我们不想检查每个值,因此仅检查第5个keyup.

Now, we should probably put our code within an event. Let's use the keyup function, but because we don't want to check every value, we'll check on only the 5th keyup.

var acceptableZipCodes = ["53782", "11709", "97035", "86531"]; 
$("#zipCode").live('keyup', function(){
   var zipCode = $(this).val();
   if(zipCode.length >4){
     if($.inArray(zipCode, acceptableZipCodes)){
       //do nothing, or do whatever you want
       //we have a return true here.
     }else{
       alert("Sorry. we don't offer products in that state.");
     } 
   }
});    

这篇关于邮编验证,显示特定状态的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆