簡體   English   中英

驗證JavaScript中的電話號碼

[英]validation for phone number in javascript

我有學生表格。 我需要驗證電話號碼。 如何使用javascript進行驗證。 我的電話表中連字符都包含在內。 這是代碼。 請給我打電話,我需要在哪里進行更改

$(function() {
            $("#XISubmit").click(function(){

    var XIStudentPhone = document.forms["XIForm"]["XIStudentPhone"].value;

        if (XIStudentPhone==null || XIStudentPhone=="") { alert("Please Enter Student Phone no"); return false; }
            document.getElementById("XIForm").submit();
            });

從“學生電話號碼”的名稱來判斷,我將假設國際化在這里不是問題。

在這種情況下,您可以執行以下操作:

<label>Phone number:
    <input type="text" name="XIStudentPhone" pattern="\d{10}" />
    (Please enter numbers only, no spaces or dashes)
</label>

這將允許使用10位數字的電話號碼,例如555-012-3456,並提供明確的指令以不包含任何符號(因此需要輸入如5550123456)。 根據您實際所在的國家/地區,您可能需要進行調整-例如在英國,您可能有10或11位數字的電話號碼,因此您將使用pattern="\\d{10,11}"

但是,重要的是要注意,這是一個假設 假定您僅與一個特定國家/地區相關,並且具有一個特定的電話號碼長度。 對於更一般的應用程序,您可能應該執行諸如pattern="\\d{5,14}"以獲得更廣泛的支持。

與往常一樣,不應信任瀏覽器端的驗證,因此請確保您也在服務器上進行驗證!

嘗試這個,

function phonenumber(inputtxt)  
{  

 var phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
 if((inputtxt.value.match(phoneno))  
    {  
  return true;  
    }  
  else  
    {  
    alert("message");  
    return false;  
    }  

}

此代碼以xxx-xxx-xxxx格式檢查電話號碼

要獲取其他格式,請訪問http://www.w3resource.com/javascript/form/phone-no-validation.php

function Validate()
        {
            var x = document.XIForm.XIStudentPhone.value;

           if(isNaN(x)||x.indexOf(" ")!=-1)
           {
              alert("Enter numeric value")
              return false; 
           }
           if (x.length>8)
           {
                alert("enter 8 characters");
                return false;
           }
           if (x.charAt(0)!="2")
           {
                alert("it should start with 2 ");
                return false
           }

        }

驗證電話號碼的簡單功能。 您可以根據所需限制進行修改。

您可以嘗試以下代碼

  XIStudentPhone = XIStudentPhone.replace(/\D/g,'');
  if(XIStudentPhone.length==0) {
        alert(XIStudentPhone + ' contains empty');
     }
    else if (XIStudentPhone.length == 10) {
        alert(XIStudentPhone + ' contains 10 digits');
     }
     else {
        alert(XIStudentPhone + ' does not contain 10 digits');
     }

您可以在html5中使用新的輸入類型。

<input type='tel' pattern='[\+]\d{2}[\(]\d{2}[\)]\d{4}[\-]\d{4}' title='Phone Number (Format: +99(99)9999-9999)'>

您可以根據需要修改模式。

這是jsFiddle http://jsfiddle.net/shyamchandranmec/aLMwq/

這是有效的電話號碼 根據示例

+99(99)9999-9999

暫無
暫無

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

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