...

View Full Version : validate numbers



urgido
07-29-2006, 08:30 AM
How I Can validate only numbers using the next format?


if (theForm.username.value == "")
{
alert("Please enter a value for the \"Username\" field.");
theForm.username.focus();
return (false);
}

Philip M
07-29-2006, 08:37 AM
if (/^\d{1,}$/.test(theField.value)) { /// match one or more digits and nothing but (if true test passes)

or

if (/\D/.test(theField.value)) { /// match any non-digit (if true test fails)

urgido
07-30-2006, 01:18 AM
what mean ".test"?

Philip M
07-30-2006, 08:49 AM
what mean ".test"?

It means what it says. Test the value contained in the field to identify whether it is true or false. In your case test that the field contains one or more digits but nothing else. If that returns true then the test passes.

This is what is called a regular expression. For more information see

http://www.javascriptkit.com/javatutors/re.shtml

urgido
07-31-2006, 12:51 AM
if (theForm.PostCode.value == "")
{
alert("Please enter a value for the \"PostCode\" field.");
} else if (/^\d{1,}$/.test(PostCode.value)) {
alert("Please enter only numbers for \"PostCode\" field.");
theForm.PostCode.focus();
return (false);
}

Is this correct? Thank you for your help master :)

Philip M
07-31-2006, 09:11 AM
if (theForm.PostCode.value == "")
{
alert("Please enter a value for the \"PostCode\" field.");
} else if (/^\d{1,}$/.test(PostCode.value)) {
alert("Please enter only numbers for \"PostCode\" field.");
theForm.PostCode.focus();
return (false);
}

Is this correct? Thank you for your help master :)


Yes, but
else if (/^\d{1,}$/.test(PostCode.value))
means that the test passes with just one numeral entered in the field.
You may prefer say
else if (/^\d{4,}$/.test(PostCode.value))
which requires at least 4 digits (e.g.9999999) and nothing but
or
else if (/^\d{4}$/.test(PostCode.value))
which requires exactly 4 digits.

But be careful - if you insist on a postcode format applicable to one country the effect may be to block users from a different country with a different postcode format (involving letters as well as numbers).

For what it is worth here is the script I use to format postcodes:-

function fixcode(pcode) {
pcode1 = pcode.value.toUpperCase();
if (pcode1 == "") { // or possibly if (pcode1.length <4); // four chars minimum
alert (Please enter a value for the PostCode field");
theForm.pcode.focus();
return false;
}
pcode1 = pcode1.replace (/[^(A-Z)(0-9)(\s)(\-)]/gi, ""); // Remove invalid characters
if (/^\D/.test(pcode1)) { // if an alpha character at start of field
pcode1 = pcode1.replace (/^(\w+)(\d)(\d)(\d)(\w+)$/gi, "$1$2$3 $4$5"); //format
pcode1 = pcode1.replace (/^(\w+)(\d)(\d)(\w+)$/gi, "$1$2 $3$4");
}
pcode.value = pcode1;
}



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum