簡體   English   中英

使用連字符驗證 Javascript 中的電話號碼

[英]validating phone number in Javascript with hyphens

好的所以我在過去 2 小時內嘗試驗證電話號碼腳本,但我似乎無法弄清楚為什么這不起作用。 最大長度是 12,我已經有一個 if 語句,它可以工作。

格式必須是: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";
     }

發生的情況是,無論我使用數字還是字母,它都會不斷彈出錯誤 window。

如果可能的話,我想學習如何在不使用 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);

第二個參數指定所取字符串的長度,而不是“結束位置”。 見參考資料

您的變量輸出值為“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);

substr的語法是string.substr(start,length)

但是,您似乎在用string.substr(start,end)調用它。

詳情請看這里

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM