-2

How can I determine if an input is a valid home phone number (without area code)?

jwpfox
  • 5,124
  • 11
  • 45
  • 42
510am
  • 7
  • 2
    Are you trying to ask about if/else syntax generally (e.g., `else` should *not* have `()` after it), or how to write the specific if condition required for phone number validation? *"valid home phone number*" - Valid in what country? – nnnnnn Oct 12 '16 at 02:34
  • Possible duplicate of [A comprehensive regex for phone number validation](http://stackoverflow.com/questions/123559/a-comprehensive-regex-for-phone-number-validation) – Nissa Oct 12 '16 at 02:37

2 Answers2

1

Regex is the best option for validating a phone number.

you can use it on the html input tag like this (this may not be supported in all browsers):

<input id="phonenum" type="tel" pattern="^\d{3}-\d{4}$" required > 

or you can test a regex string in you code like this (also, this is the correct format for you function above):

<script type="text/javascript">
     //function\\
     function validPhone(phoneNum) {
         var reg = new RegExp("^\d{3}-\d{4}$");
         if (reg.test(phoneNum)) {
             return "True";
         }
         else {
             return "False";
         }
     }
</script>

and if you want to make it short and sweet and you just need to return a bool value, you can do do this:

<script type="text/javascript">
     //function\\
     function validPhone(phoneNum) {
         var reg = new RegExp("^\d{3}-\d{4}$");
         return reg.test(phoneNum);
     }
</script>
Russell Jonakin
  • 1,716
  • 17
  • 18
  • Looks good. Though I'd put a question mark after the hyphen to allow it to be optional. Also your regex is in quotes so you need double backslash for \\d – Steve Tomlin Dec 26 '20 at 06:39
0

You should only have parenthesis/brackets after an else if statement. Not an else statement.

Example: If(true){ }else if(true){ }

Or

If(true){
}else{
}

NOT if(true){ }else(){ }

Steve Tomlin
  • 3,391
  • 3
  • 31
  • 63