DEV Community

Cover image for How to check if a string is a valid Indian mobile number in JavaScript?
MELVIN GEORGE
MELVIN GEORGE

Posted on • Originally published at melvingeorge.me

How to check if a string is a valid Indian mobile number in JavaScript?

Originally posted here!

To check if a string is a valid Indian mobile number in JavaScript, we can use a regex expression to match numbers that start with either of number 6, 7, 8 or 9 then checks if it has a total of 10 number digits in it.

TL;DR

// Regular expression to check if string is a Indian mobile number
const regexExp = /^[6-9]\d{9}$/gi;

// String with Indian mobile number
const str = "9207323601";

regexExp.test(str); // true
Enter fullscreen mode Exit fullscreen mode

This is the regex expression for matching almost all the test cases for a valid Indian mobile number in JavaScript.

// Regular expression to check if string is a Indian mobile number
const regexExp = /^[6-9]\d{9}$/gi;
Enter fullscreen mode Exit fullscreen mode

This will match all the 10 number digits which starts with number 6, 7, 8 or 9 and then checks if the remaining numbers are of 9 digits.

Now let's write a string with an Indian mobile number like this,

// Regular expression to check if string is a Indian mobile number
const regexExp = /^[6-9]\d{9}$/gi;

// String with Indian mobile number
const str = "9207323601";
Enter fullscreen mode Exit fullscreen mode

Now to test the string, we can use the test() method available in the regular expression we defined. It can be done like this,

// Regular expression to check if string is a Indian mobile number
const regexExp = /^[6-9]\d{9}$/gi;

// String with Indian mobile number
const str = "9207323601";

regexExp.test(str); // true
Enter fullscreen mode Exit fullscreen mode
  • The test() method will accept a string type as an argument to test for a match.
  • The method will return boolean true if there is a match using the regular expression and false if not.

See the above example live in JSBin.

If you want this as a utility function which you can reuse, here it is,

/* Check if string is a valid indian mobile number */
function checkIfValidIndianMobileNumber(str) {
  // Regular expression to check if string is a Indian mobile number
  const regexExp = /^[6-9]\d{9}$/gi;

  return regexExp.test(str);
}

// Use the function
checkIfValidIndianMobileNumber("9207323601"); // true
checkIfValidIndianMobileNumber("92073236011"); // false
Enter fullscreen mode Exit fullscreen mode

That's all! 😃

Feel free to share if you found this useful 😃.


Top comments (0)