1

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.

3
  • 6
    That code works correctly. Your bug is elsewhere, I think. Commented Nov 18, 2012 at 18:44
  • What number did you use? Also, jquery is not the magical solution to all problems. Careful debugging is. Commented Nov 18, 2012 at 18:46
  • Next time use actual code that represents the problem. Commented Nov 18, 2012 at 19:20

1 Answer 1

6

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/

Sign up to request clarification or add additional context in comments.

14 Comments

yep, you are right the problem is i was checking .text() instead of .val() . my bad programming for long hours causes this stupid mistakes. Thanks alot
@AshkanMobayenKhiabani, Atif: Both .text() and .val() return a string. The actual issue is that .text() doesn't return the value, so you were getting an empty string, not a number.
@Asad, sorry about that, was trying to demonstrate quickly and copy and pasted everything..
@user1689607 this is what exactly happen ... if answer +1
@NullPointer: Thanks, but I'd rather see the question deleted to reduce SO clutter.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.