Webnerdoz Webnerdoz - 4 months ago 29
Javascript Question

Validate (Australian) Phone Numbers in Javascript

I need to validate Australian phone numbers (e.g.

02[3-9]\d{7}
or
07[3-9]\d{7}
or
04[\d]{8}
) in JavaScript.

Requirements:


  • must be 10 digits

  • no commas

  • no dashes

  • no + in front

  • must begin with 0



At the moment I can validate required fields and email address but I want to add phone number validation.

<html>
<head>

<script type="text/javascript">
function validateForm() {
var x=document.forms["form3"]["name"].value;
if (x==null || x=="") {
alert("Name must be filled out");
return false;
}
var s=document.forms["form3"]["phone"].value;
if (s==null || s=="") {
alert("Please Enter your Phone or Mobile Number - Preferably Phone Number");
return false;
}
var s=document.forms["form3"]["email"].value;
if (s==null || s=="") {
alert("Please Enter a valid email address");
return false;
}
var k=document.forms["form3"]["email"].value;
var atpos=k.indexOf("@");
var dotpos=k.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=k.length) {
alert("Email Address is Not Valid. Please provide your correct email address.");
return false;
}
}
</script>
</head>
<body>

<form action="/thank-you.php" name="form3" method="post" onsubmit="return validateForm();" >
Your name* <input type="text" name="name" />
Phone number* <input type="text" name="phone" />
Email* <input type="text" name="email" />
<input type="submit" value="sumbit" name="submit" class="button" onclick="javascript:return validateMyForm();" /><input type="reset" value="Reset" class="resetbutton" />
</form>

</body>
</html>


Can someone help out?

Answer

Here is a regex that I would recomment

var pattern = /^0[0-8]\d{8}$/g;

So input must start with 0, and followed by a digit and it must be one between 0-8. Then it must have 8 more digit numbers.

Valid phone number examples:

0010293999 (ok)

0110293999 (ok)

0210293999 (ok)

0910293999 (nope)

//Implementation

 ........
 var phoneNumber =document.forms["form3"]["phone"].value;
 var phonePattern = /^0[0-8]\d{8}$/g;
 //phone number is not valid. Please notice that you don't need to check if it's empty or null since Regex checks it for you anyways
 if (!phoneNumber.test(phonePattern))
   {
   alert("Please Enter your Phone or Mobile Number - Preferably Phone Number");
   return false;
   }
 ..........

---- Edit

........
     var phoneNumber =document.forms["form3"]["phone"].value;
     var phonePattern = /^0[0-8]\d{8}$/g;
     //phone number is not valid. Please notice that you don't need to check if it's empty or null since Regex checks it for you anyways
     if (!phonePattern.test(phoneNumber))
       {
       alert("Please Enter your Phone or Mobile Number - Preferably Phone Number");
       return false;
       }
     ..........