簡體   English   中英

需要電話驗證10位數字,空格和連字符

[英]Need phone validation for 10 digits, spaces and hyphens

我環顧四周,看到了很多正則表達式示例,但沒有一個我要找的。 我需要驗證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 = '';
    }

謝謝!

這就是我要做的:

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 = '';
    }
}       

您只需將\\D替換為空白...這樣就只剩下數字了。

暫無
暫無

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

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