验证文本框条目用逗号分隔的3位数字

时间:2012-10-15 20:48:50

标签: php javascript jquery html

我在注册表格上有一个收集电话区号的文本框 - 我的智能自己认为我的客户不会输入5位数的邮政编码而不是3位数的区号,所以现在我需要制作一个创建一个jquery或javascript函数来验证条目是否在###,###,###,###,### ...格式中,对它们可以输入的区号的数量没有限制。 问题是我不知道代码应该怎么做 - 任何想法 我的文字框

<input type="text" id="acode" name="acode" />

我很感激

已完成的代码

HTML

  <label for="acode">Enter area codes separated by commas (757,804,252,###):</label>
  <input type="text" id="acode" name="acode" onblur="valarea(this.form)"/>

的Javascript

<script>
function valarea(form)
{
inputvalue =form.acode.value;
var regexp = /^\d{3}(?:,\d{3})*$/;
if (inputvalue != "")
{
if (regexp.test(inputvalue)) {
//nothing happens
} else {
alert('You have entered an invalid value, you should have listed 3 digit telephone area codes for the areas you are interested in shopping separated by commas (757,804,252,###) Please Correct the problem before continuing')
form.acode.focus()
}
}
}

2 个答案:

答案 0 :(得分:1)

使用正则表达式:

var regexp = /^\d{3}(?:,\d{3})*$/;
if (regexp.test(inputvalue)) {
  // Valid, do something with it...
} else {
  // Invalid, show error.
}

有关Javascript中正则表达式的更多信息,请see the MDN page for regular expressions

答案 1 :(得分:0)

不确定您是否需要它,但如果您想验证当前区号的列表,我可以向您发送一个列表。我为GreatData.com工作,我们维护美国和加拿大的现行区号。只需访问该网站获取联系信息并要求提供文件。

不知道您的确切应用,但您可能有一个选项列表,他们可以选择适当的区号并自行构建逗号分隔列表。