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的情況下做到這一點,如果可能的話。 謝謝。
請記住很多用戶不知道的「整數」是什麼;考慮使用更友好的語言。另外,不僅代碼重複,而且可以爲單個字段獲取三條相同的消息。 – 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