Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I validate a phone number with javascript?

Would someone a little smarter than myself be able to help me with this function? Its purpose is to validate a text input in a form, a phone number field that will only accept 0-9, dash and dot. The HTML calls the function fine.

function validateFeedback() {
    var phone = document.getElementById("phone");
    var validNumber = "0123456789.-";
    for (i = 0; i < phone.length; i++); {
        if (validNumber.indexOf(phone.charAt(i)) == -1); {
            alert("You have entered an invalid phone number");
            return false;
        }
    }
    return true;
}

Thanks so much for any help.

like image 314
user1395909 Avatar asked May 16 '12 10:05

user1395909


People also ask

How do I validate a mobile number?

Mobile Number validation criteria: The first digit should contain number between 7 to 9. The rest 9 digit can contain any number between 0 to 9. The mobile number can have 11 digits also by including 0 at the starting. The mobile number can be of 12 digits also by including 91 at the starting.

How do you write a validation rule for a phone number?

Validates that the Phone number is in (999) 999-9999 format. This works by using the REGEX function to check that the number has ten digits in the (999) 999-9999 format. Error Message: US phone numbers should be in this format: (999) 999-9999.


2 Answers

Regular expressions should help ;)

I'm sorry I haven't tried to run this code, but it should be OK.

function validateFeedback(){
    var phone = document.getElementById("phone");
    var RE = /^[\d\.\-]+$/;
    if(!RE.test(phone.value))
    {
        alert("You have entered an invalid phone number");
        return false;
    }
    return true;
}
like image 82
Jiří Herník Avatar answered Sep 29 '22 04:09

Jiří Herník


try like this:

function validateFeedback()
    {
    var phone = document.getElementById("phone");
    var validNumber = "0123456789.-";


    for(i = 0; i < phone.length; i++) {
            if(validNumber.indexOf(phone.charAt(i)) == -1) {
                    alert("You have entered an invalid phone number");
                    return false;
                }
            }

        return true;
    }

there are ; out of place ...

like image 23
Aleksandrenko Avatar answered Sep 29 '22 04:09

Aleksandrenko