View Full Version : Number validation

10-31-2009, 03:12 PM
Hi all,

I am using the following code to validate a phone number field

if(isNaN(number.value) && number.length !=11)
valid = false;
alert("Please ammend your number");


As you can see I am trying to determine the entry is actually a number and also the length of the number has to be 11 digits.

The code validates whether the entered value is 11 digits long but it allows the entry to be 11 alphabetical characters which should not be allowed. Why is this?

Any help would be appreciated


10-31-2009, 04:43 PM
First of all, number is an at least partially reserved word, so really shouldn't be used as a name for a variable or element or anything else other than to represent the Global number object. Second, where is the value you want stored? Is it in number.value or in number?

Now I'm thinking that you don't really mean 11 numbers and no other characters, because that's not how most phone numbers are usually represented, but if you do:

function numVal(el){
alert('Enter only 11 numbers please');

<input type="text" onchange="numVal(this);">

The test /^\d{11}$/ is a regular expression and may be altered to allow only your preferred format for the phone number, or even to allow a few various acceptable formats. For me to write that for you, I would need to know the format(s). But be careful, often the 'rules' for validation used on forms can be too constricting or too lenient, think carefully about just what you want these to be in this case.

Also, if this is being stored for later use on the server side, there should also be validation on the server side.

11-09-2009, 01:29 AM
All I am using it for is for a phone number field . . Phone numbers are all 11 digits long so for example I require this format


All i want validated is the restrictions on illegal characters and so that the number entered is 11 digits long thus resulting in a valid phone number


11-09-2009, 03:05 AM
In that case, what I posted will work for you. But phone numbers come in many forms, depending upon cultural norms. Where I'm from, this is a common format:


as is:

(###) ###-####

and a few others. This of course doesn't include the country code, which may include 1 or more digits.

11-10-2009, 11:30 AM
Cheers mate, it worked

Many thanks