Home > front end >  Valid a phone number using JavaScript
Valid a phone number using JavaScript

Time:06-08

I'm trying to validate phone number such as 123-456-7891 by using JavaScript and here my code :

<script>
function validphnum() 
{
  var x = document.getElementById("phnum").value;
  var format = [0-9]{3}-[0-9]{3}-[0-9]{4};
  if (format.test(x))
      alert("Valid Phone Number");
  else
      alert("Invalid Phone Number");
}
</script>
<body>
<div > 
<label for="phnum">Enter Phone Number (XXX-XXX-XXXX): </label> 
<input type = "text" id = "phnum"> 
<button onclick="validphnum()" type="button">Submit</button>
</div>
</body>

CodePudding user response:

A couple of small changes to the format regex variable should fix this.

We need to add / before and after the expression to ensure it's recognized as a regular expression.

Also the boundary assertions ^ and $ at either end to ensure the user can't enter characters before or after the phone number.

function validphnum() 
{
  var x = document.getElementById("phnum").value;
  var format = /^[0-9]{3}-[0-9]{3}-[0-9]{4}$/;
  if (format.test(x))
      alert("Valid Phone Number");
  else
      alert("Invalid Phone Number");
}
<body>
    <div > 
        <label for="phnum">Enter Phone Number (XXX-XXX-XXXX): </label> 
        <input type = "text" id = "phnum"> 
        <button onclick="validphnum()" type="button">Submit</button>
    </div>
</body>

CodePudding user response:

/^[\ ]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$/im
  • Related