View Full Version : Form phone number validation

07-14-2007, 03:06 PM
Hi all,
I need to get a form validation script working. What I would like is for the script to ensure that the phone number entered is either seven or ten digits. If it is seven digits, a default area code will automatically be added to the front of the number.

Any ideas on how to do this. I've hit a mental brick wall. The rest of the script is just checking that a valid email address has been entered

Thanks for any help.


07-14-2007, 10:01 PM
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<script language="JavaScript" type="text/javascript">

function zxcVerify(zxcfrm){
var zxcels=zxcfrm.elements;
var zxcmess=['Errors:'];
for (var zxc0=0;zxc0<zxcels.length;zxc0++){
if (zxcels[zxc0].className.match('Phone')){
var zxcdata=zxcels[zxc0].className.split('#');
if (zxcels[zxc0].value.length<zxcdata[1]||zxcels[zxc0].value.length>zxcdata[2]){
zxcmess.push((zxcels[zxc0].title||zxcels[zxc0].name||'')+' '+zxcdata[1]+' to '+zxcdata[2]+' Digits Required');
else if (zxcels[zxc0].value.length==zxcdata[1]){
if (zxcmess.length>1){
return false
return true;


<form onsubmit="return zxcVerify(this);" action="http://www.vicsjavascripts.org.uk" >
<input title="Phone Number" class="RealClass Phone#7#10#023#" type="text" value="12as3"/>
<input type="submit" name="" value="Submit" />


07-14-2007, 11:57 PM
Not all phone numbers are that length. Phone numbers around here are all 8 digits long and elsewhere in the world are all different lengths. It is the WORLD WIDE web and unless your pages relate specifically to one place and use an appropriate domain name to indicate that the site is specific to that country then you will have visitors from all over the world complaining that your validation is rejecting their valid input.

Philip M
07-15-2007, 04:01 PM
I agree with felgall, not all phone numbers are 10 digits.

But here is what you want:-

if (/(^[0-9]{7})$/gi.test(phoneNumber.value)) {
phoneNumber.value = "012" + phoneNumber.value // add prefix
return true;
if (/(^[0-9]{10})$/gi.test(phoneNumber.value)) {
return true;
else {return false}

07-17-2007, 12:48 PM
I haven't had access to the computer for a couple of days so it's a belated...Thanks! Very much appreciated.