2014-02-19 69 views
-1

我環顧四周,看到了很多正則表達式的例子,但沒有一個我正在尋找。我需要驗證10位數字,允許空格和破折號,但不包括括號或其他字符。需要手機驗證10位數字,空格和連字符

以下是我目前使用:

function validatePhone(phone) { 
    var error = ""; 
    var stripped = phone.value.replace(/^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/, ''); 

    if (phone.value == "") { 
     document.getElementById('phone-error').innerHTML = "Please enter a phone number"; 
     phone.style.background = 'Yellow'; 
     var error = '6'; 
    } else if (isNaN(parseInt(stripped))) { 
     var error = "5"; 
     document.getElementById('phone-error').innerHTML = "The phone number contains illegal characters."; 
     phone.style.background = 'Yellow'; 
    } else if (stripped.length < 10) { 
     var error = "6"; 
     document.getElementById('phone-error').innerHTML = "The phone number is too short."; 
     phone.style.background = 'Yellow'; 
    } else { 
     phone.style.background = 'White'; 
     document.getElementById('phone-error').innerHTML = ''; 
    } 

謝謝!

+0

這顯著更容易只是把一小紙條文本框說下「請只輸入數字 - 沒有空格或符號」,然後檢查你有10個數字。 –

+2

爲什麼要這樣驗證?電話號碼不同。您的10位驗證已經失敗了我的11位手機號碼。 – 2014-02-19 01:16:34

+1

什麼不工作? – Robin

回答

0

你可以用空白空間替換\D ...所以你只剩下數字了。

2

這是我會怎麼做:

function validatePhone(phone) { 
    var error = ""; 
    var stripped = phone.value.replace(/\D+/, ''); // strips all non digit characters 

    if (stripped == "") { 
     document.getElementById('phone-error').innerHTML = "Please enter a phone number"; 
     phone.style.background = 'Yellow'; 
     error = '6'; 
    } else if (phone.value.match(/[^\d() .-]/)) { 
     error = "5"; 
     document.getElementById('phone-error').innerHTML = "The phone number contains illegal characters."; 
     phone.style.background = 'Yellow'; 
    } else if (stripped.length < 10) { 
     error = "6"; 
     document.getElementById('phone-error').innerHTML = "The phone number is too short."; 
     phone.style.background = 'Yellow'; 
    } else { 
     phone.style.background = 'White'; 
     document.getElementById('phone-error').innerHTML = ''; 
    } 
}  
+0

你能解釋一下這是什麼嗎?我是新來的正則表達式。 – justinae

相關問題