Function to validate phone number with RegEx

Hi everyone:

Here’s a function that validates this exact pattern for a telephone number: (234) 567-8901

I’d like to know why this function returns undefined in the console:

function validPhoneNumber(phoneNumber){
    //Return whether phoneNumber is in the proper form
  var phonePattern = /^\((\d{3}\))(\s{1})(\d{3})(-{1})(\d{4})/;
  var validPhone = phonePattern.test(phoneNumber);
  var result = false;
  if (validPhone){
    var result = validPhone;
    return result;
  }
}
undefined
validPhoneNumber("(234) 567-8901")

Thanks!

1 Like

the function only executes the return statement when the validation succeeds. hence if it fails it returns nothing a.k.a. undefined.

though that’s not the observed problem. it works perfectly fine, but a function definition usually doesn’t create a console output.

and for testing (that is worth the name) at least rely on console.log() (or similar) … or use a testing framework like mocha (there are many more, use the one you feel comfortable with)

1 Like

Thanks. I understand undefined now.

What about the regular expression? It should pass the following tests:

validPhoneNumber(“(123) 456-7890”) => returns true
validPhoneNumber(“(1111)555 2345”) => returns false
validPhoneNumber(“(098) 123 4567”) => returns false

But it seems there’s a test case where it should be false and instead it’s true…

I see that I could write:
[0-9]{3} or /d{3}. Is there any difference between the two?

Thanks again.

1 Like

sure. one tests for 3 successive digits, the other for a slash followed by 3 "d"s

I have to say, though, that your RegExp is unnecessarily complicated. you don’t need groups and {1} is superfluous at least.

1 Like

sorry, it should have been \d{3}.

1 Like

No difference, it just saves you typing three characters

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.