使用连字符在Javascript中验证电话号码
问题描述:
ok因此,我试着验证过去2小时的电话号码脚本,但似乎无法弄清楚为什么这不起作用。最大长度是12,我已经得到了一个if语句,这是有效的。使用连字符在Javascript中验证电话号码
的格式必须为:NNN-NNN-NNNN
var tele = document.pizza.field03; //store phone number
var fone = tele.value //store values of variable tele in fone
var acode = "";
var midnum = "";
var lasnum = "";
var hyphen = "";
var hyphen2 ="";
acode=fone.substr(0,3);
hyphen=fone.substr(3,4);
midnum=fone.substr(4,7);
hyphen2=fone.substr(7,8);
lasnum=fone.substr(8);
else if (isNaN(acode))
{
errMessages += "<li>Please use integer numbers only</li>\n";
errMessages += "<li>ex: 1 2 3 4 5 </li>\n";
}
else if (isNaN(midnum))
{
errMessages += "<li>Please use integer numbers only</li>\n";
errMessages += "<li>ex: 1 2 3 4 5 </li>\n";
}
else if (isNaN(lasnum))
{
errMessages += "<li>Please use integer numbers only</li>\n";
errMessages += "<li>ex: 1 2 3 4 5 </li>\n";
}
编辑 *
else if (hyphen.indexOf('-') ==-1) //checking for hyphen
{
errMessages += "<li>You need a hyphen after the area code</li>\n"
errMessages += "<li>ex: areacode-nnn-nnn</li>\n"
}
else if (hyphen2.indexOf('-') ==-1)
{
errMessages += "<li>You need a hyphen after the middle 3 digits</li>\n";
errMessages += "<li>ex: 416-mid-1234</li>\n";
}
发生的事情是我是否使用数字或字母,它会不断出现上错误窗口。
我想学习如何在不使用RegEx的情况下做到这一点,如果可能的话。 谢谢。
答
acode=fone.substr(0,3);
hyphen=fone.substr(3,4);
midnum=fone.substr(4,7);
hyphen2=fone.substr(7,8);
lasnum=fone.substr(8);
第二个参数指定字符串的长度采取,不是“结束位置”。 (See reference)
您的变量与值'nnn','-nnn','nnn-nnnn','-nnnn'和'nnnn'一起出来。
acode=fone.substr(0,3);
hyphen=fone.substr(3,1);
midnum=fone.substr(4,3);
hyphen2=fone.substr(7,1);
lasnum=fone.substr(8);
+0
!谢谢你,那是我的问题。所以在逗号后面的数字是字符串的长度好吧,我明白这一点。谢谢!! – Umeed 2012-04-07 22:42:58
请记住很多用户不知道的“整数”是什么;考虑使用更友好的语言。另外,不仅代码重复,而且可以为单个字段获取三条相同的消息。 – 2012-04-07 22:38:30
@DaveNewton是的,我只是把东西扔在那里和LOL @ ew部分......是的,至于重复的代码,我不知道如何把所有的东西放在一个。 – Umeed 2012-04-07 22:39:50
为什么你不想使用正则表达式?你可以使用正则表达式在一行中验证整个事件,并用一个“电话号码必须是格式为nnn-nnn-nnnn”的消息来替换所有的错误消息... – nnnnnn 2012-04-07 22:50:39