1

we are trying to find if the given string is a valid indian mobile number or not

valid indian mobile number

  1. starts with 7 or 8 or 9
  2. followed by 9 same or different numbers

here is my JavaScript for matching it, but unfortunately it returns false even when number is correct

var mobile_number = $('#number').val();
var mobile_regex = new RegExp('/^[789]\d{9}$/');
if(mobile_regex.test(mobile_number) == false) {
    console.log("not valid");
} else {
    console.log("valid");
}
7
  • What is a correct number? https://regex101.com/r/yW6vC2/1 Here I can see that 7123456789 is a match, for example. Are there any other symbols at the front/back of the number? Commented Jun 30, 2016 at 11:41
  • var mobile_regex = /^[789]\d{9}$/; Commented Jun 30, 2016 at 11:41
  • @MariaDeleva anything followed by 7,8,9 but length must be equal to 10 Commented Jun 30, 2016 at 11:43
  • @anubhava what is the difference with the current approach? Just wondering: doesn't RegExp() allow \d? Commented Jun 30, 2016 at 11:44
  • 2
    @fedorqui: 2 problems. RegExp doesn't need regex delimiter / and it requires double escaping. Commented Jun 30, 2016 at 12:04

2 Answers 2

3

Your code has two problems. If you're using a RegExp object, you don't need / characters, and the \ character needs to be escaped.

This would work:

var mobile_regex = new RegExp("^[789]\\d{9}");

Alternatively, if you want to use the other format, this would work:

if(!mobile_number.match(/^[789]\d{9}/)) {
    console.log("not valid");
} else {
    console.log("valid");
}
Sign up to request clarification or add additional context in comments.

2 Comments

why when using new RegExp does \d need to be escaped. /?
It's just the \ that needs to be escaped. The reason is that \ is an escape character in javascript strings.
2

You can try this

   var mobile_number = $('#number').val();
   var mobile_regex = new Regex("^[7-9][0-9]{9}$")
   if(mobile_regex.test(mobile_number) == false) {
   console.log("not valid");
   } else {
    console.log("valid");
   }

Comments

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.