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");
}
runningmark
  • 757
  • 4
  • 9
  • 26

2 Answers2

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");
}
Chris Lear
  • 6,057
  • 1
  • 14
  • 25
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");
   }
Nikhil Ghuse
  • 1,218
  • 12
  • 29