Javascript Phone Number Validation

By May 7, 2012 JavaScript

JavaScript Phone Number Validation 

Notes : Fresher Need to Understand Regular Expression.

We made Phone number validation example after lots of trial, help using regular expression.
you can check with following format.
xxx-xx-xxxxxx

<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”>
<html>
 <head>
  <title> Phone Number Validation Example </title>
  <meta name=”Generator” content=”EditPlus”>
  <meta name=”Author” content=””>
  <meta name=”Keywords” content=””>
  <meta name=”Description” content=””>

  <script type=”text/javascript”>
  <!–
    function ValidateForm(){
        var ValidString = document.forms[“myform”][“txtPhone”].value;
        var regexObj = /^(?([0-9]{3}))?[-. ]?([0-9]{2})[-. ]?([0-9]{8})$/;

        if (regexObj.test(ValidString)) {
            var formattedPhoneNumber =
                subjectString.replace(regexObj, “($1) $2-$3”);
                alert(“Success”);
        } else {
            alert(“Invalid phone number”);
            return false;
        }
    }
  //–>
  </script>
 </head>

 <body>
  <form id=”myform” name=”myform” method=”POST” action=”” onsubmit=”return ValidateForm();”>
    <input type=”text” name=”txtPhone” id=”txtPhone”>
    <input type=”submit” name=”submit” id=”submit” value=”I Agree”>
  </form>
 </body>
</html>

Leave a Reply