-1

Here is my code

var _phonenumber = '09000000000';
if _phonenumber.match(/\A0[5789]0\d{8}\z/)
  console.log('valid');
else
  console.log('invalid)';

But if I input correct phone, it still print invalid 09000000000

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563

1 Answers1

1

The match() method retrieves the matches when matching a string against a regular expression.

If the string matches the expression, it will return an Array containing the entire matched string as the first element, followed by any results captured in parentheses. If there were no matches, null is returned.

In your case, you are missing the parenthesis around match.

var _phonenumber = '09000000000';
if(_phonenumber.match(/\A0[5789]0\d{8}\z/))
  console.log('valid');
else
  console.log('invalid');
  
console.log(_phonenumber.match(/\A0[5789]0\d{8}\z/));

The test() method executes a search for a match between a regular expression and a specified string. Returns true or false.

Using test() will be better for your use case.

var _phonenumber = '09000000000';
if(/\A0[5789]0\d{8}\z/g.test(_phonenumber))
  console.log('valid');
else
  console.log('invalid');
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51