JavaScript: Validate a telephone number.

Posted October 2nd, 2010


The following JavaScript will validate if a 10 digit phone number was supplied once the form is submitted.

<head>
 
...
 
<script language="JavaScript" type="text/javascript">
function nameCheck() {
}
function teleCheck(teleStr) {
alert(teleStr);
    var stripped = teleStr.replace(/[\(\)\.\-\ ]/g, '');   
    if (teleStr == "") {
        alert("You must supply a phone number.");
        return false;
    } else if (isNaN(parseInt(stripped))) {
        alert("The supplied phone number contains illegal characters.");
        return false;
    } else if (!(stripped.length == 10)) {
        alert("Supplied phone number is the wrong length.\nBe sure to included an area code.");
        return false;
    }
    return true;
}
</script>
 
...
 
</head>
 
...
 
<body>
 
...
 
<form id="form1" name="form1" method="post" onSubmit="return teleCheck(this.telephone.value)" action="">
 
...