Ashkan Mobayen Khiabani
Ashkan Mobayen Khiabani

Reputation: 34152

Javascript Regex: Validate phone number

I want to validate a 11 digit phone number that must start with 09 (i.e. 09123456789) using javascript for client side check.

this is my code:

function validatePhone(number) {
    var re = /^09[0-9]{9}$/;
    return re.test(number);
}

It worked correctly as far as I know at first but now it return invalid for any number I use. Does anyone know what is wrong with my code? By the way as I'm using jQuery, if there is a better way with jquery that would be much better.

Upvotes: 1

Views: 2600

Answers (1)

Atif
Atif

Reputation: 10880

I am assuming you are sending an integer in the argument, pass it as a string

function validatePhone(number) {
    var re = /^09[0-9]{9}$/;
    return re.test(number);
}

​alert(validatePhone('09123456789'));​​​
// returns true    
alert(validatePhone(09123456789));    
// returns false    ​

http://jsfiddle.net/3bFwd/

Upvotes: 6

Related Questions