...

View Full Version : Testing HTML form for numeric values



navaqeel
06-07-2007, 12:13 AM
Hi everyone:

Just wondering if anyone can help me with this. I've created an HTML form and written a javascript that tests to make sure users don't leave any fields blank when submitting the form. One of the fields on the form is the phone_number. I want to make sure that users only enter the numeric value in this field. If for example, they enter some letters in the phone_number field then javascript should prompt them to only enter the numbers. How would I do this? Here's a code I am using to make sure fields are NOT left empty:

if (formObj.phone_number.value == "") {
window.alert("Please enter a valid phone number along with the area code");
formObj.phone_number.focus();
return false;
}

Thanks for your help and cooperation in advance.

cyberlogi
06-07-2007, 01:22 AM
Use a regex to test if it is a valid phone #.


var regex = /^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,5})|(\(?\d{2,6}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$/;
regex .test(val);

this will except mode common phone formats and international phone formats. erase any phone # that doesn't work and tell your user to use a format like "999-888-7777"

brandonH
06-07-2007, 01:52 AM
can also use isNaN.

example:


if(isNaN(element.value)){alert('the value is not a number');}

Philip M
06-07-2007, 07:32 AM
As with most other validations, over-elaboration of telephone number validation can be counter-productive. My UK (ex-directory) phone number is something like 01485 765387 (not normally with a hyphen). Cyberlogi's regex does not accept this.

The main risk is that the user simply enters the wrong number (transposed digits etc.) and nothing can prevent this. In fact I often deliberately enter a wrong number where the field is compulsory to eliminate unwanted spam calls.

I would advise that telephone number validation is simply a check that the input box contains only numbers (without specifying how many or their precise format which varies from country to country), and also + (international prefix), - (hyphens) and/or spaces.

- and space can be stripped out if necessary.

The regex is:-

if (/[^0-9\s\-\+]/gi.test(phoneNumber.value) || (phoneNumber.value.length <9 )) { /// only digits, space, hyphen and plus sign allowed. Minimum of 9 characters.

You can test your regular expressions at: http://www.ogauge.co.uk/regextester.html



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum