0

The following is my code:

<html>
<title>Validate Phone Number</title>
<head>
<script>
function testnumber() {
    var ph = new RegExp("^[789]\d{9}$");
    num = {10 digit phone number}
    alert(ph.test(num));
}
testnumber();
</script>
</head>
<body>
</body>
</html>

I want to validate mobile phone number which starts with 7/8/9 and is 10 digit. But it alerts false for any phone number given as input.

Please tell me where am I going wrong. Thanks in advance.

gurvinder372
  • 66,980
  • 10
  • 72
  • 94
Yash Parekh
  • 129
  • 1
  • 10

3 Answers3

2

Try this, your formatting was slightly off:

function testnumber() {
    var ph = new RegExp(/^[789]\d{9}$/);
    num = 7123435498; // example number
    alert(ph.test(num));
}
testnumber();
Kwesi
  • 607
  • 1
  • 9
  • 21
1

You can try this HTML only option too

<html>
<body>
<form action="">
 Phone number: <input type="text" pattern="[7-9]{1}[0-9]{9}" title="Enter valid number">
  <input type="submit">
</form>
</body>
</html>
Gowtham Shiva
  • 3,802
  • 2
  • 11
  • 27
0

Your existing regex doesn't work for following reason

\d in a string literal is evaluated to d

Hence, you can take following two approaches

1) Try this

var ph = new RegExp("^[789]{1}[0-9]{9}$");
var num = "7894543542";
console.log( ph.test(num) ); //true
  • ^ matches start of the string
  • [789] matches one of 7,8 or 9
  • [0-9]{9} matches 9 digits
  • $ matches end of the string

2) Your regex works fine as well if you passed a regex literal instead of a string.

var ph = new RegExp(/^[789]\d{9}$/);
var num = "7894543542";
ph.test(num); //true
gurvinder372
  • 66,980
  • 10
  • 72
  • 94