-1

I am trying to validate telephone number in this format : (xxx) xxx-xxxx. For that I have used regular expression but it doesn't validate when I enter incorrect format and click on submit it doesn't show any error. Can anyone help me to identify an issue?

code:

<!DOCTYPE html>
<html>
<head>
 <title>NumerValidation</title>
</head>
<body>
  <form name="myform" id="myform" action="" onsubmit="return validateForm()" method="post">
   <table cellspacing="2" cellpadding="2" border="0">
   <tr>
    <td align="right">Telephone number</td>
    <td><input type="text" name="phone" size="28" placeholder="(555) 555-5555"/></td>
   </tr>
   <tr>
    <td align="right"></td>
    <td><input type="submit" value="Submit" /> </td>
   </tr>
  </table>
  </form>

  <script>

   function validateForm() {

   var phone = document.myform.phone; 
   var regPhone = /^\(?[(]?[0-9]{3}[)]?[-\s]?[0-9]{3}[-]?[0-9]{4}$/im;

    //var phone = /^\(?([0-9]{3})\)?[-]?([0-9]{3})[-]?([0-9]{4})$/;  
    if(phone.value.match(regPhone)) 
    {  
     return true;  
    }  
    else  
    {  
     window.alert("Please enter Telephone number in (xxx) xxx-xxxx format.");  
     return false;  
    } 
   } 
  </script>

</body>
</html>
Riya
  • 415
  • 9
  • 23

1 Answers1

0

use this regular expression

^\(\d{3}\)\s{0,}\d{3}\s{0,}-\s{0,}\d{4}$

it matches

(111)111 - 1111
(111) 111 - 1111
(111) 111- 1111
(111) 111- 1111
(111) 111-1111
(111) 111 - 1111

incase the user adds spaces at the beginning or end of the phone number, you have to trim it with

value = value.trimLeft();
value = value.trimRight();

if you don't trim white spaces at the beginning and end of the input, the regexp will fail even if the user inputs valid number

0.sh
  • 2,659
  • 16
  • 37