...

View Full Version : Javascript RegExp in Forms



Experimental
08-26-2010, 12:02 PM
I cannot get the result right. I write area and phone by numbers but it still gives me error


function validate_text(field,alerttext) {
with(field) {

var re = /[a-zA-Z]/g;
if(re.test(field)) { return true;}else{alert(alerttext);return false;}
}
}
function validate_number(field,alerttext){
with(field) {

var re = /[0-9]/g;
if(re.test(field)) { return true;}else{alert(alerttext);return false;}
}
}



function validateForm(thisForm){
with(thisForm)
{
if(validate_number(area,"wrong area code") == false) {

area.focus();return false;
}
if(validate_number(phone,"wrong phone") == false) {

phone.focus();return false;
}
if(validate_text(name_surname,"wrong name") == false) {

name_surname.focus();return false;
}

}
}



...<b>Name Surname :</b><input style="margin-left:10px;" type="text" name="name_surname"/>
<br /><br />
<b>phone :</b><input type="text" style="margin-left:19px;" maxlength="4" size="4" name="area" />
-<input type="text" style="margin-left:5px;" maxlength="7" size="10" name="phone" /><br /><br />....

Arty Effem
08-26-2010, 03:07 PM
if(re.test(field.value)) Repeat throughout.

Old Pedant
08-26-2010, 09:30 PM
That validation is useless:


function validate_number(field,alerttext){
with(field) {

var re = /[0-9]/g;
if(re.test(field.value)) { return true;}else{alert(alerttext);return false;}
}
}

That will *PASS* any field value that has even ONE digit in it!

So if the user enters "a%*(#)!4xyz" it will PASS because of the '4" in there.

A better test might be:

function validate_number(field,alerttext)
{
var re = /[^0-9]/;

if( ! re.test(field.value) ) return true;

alert(alerttext);
return false;
}

Which will barf if it finds *ANY* non-digit characters.

But that's not a good test for phone numbers, as people are used to putting in ( ) and - and . and maybe + into phone numbers.

So you should think more about what you really want to allow and really want to reject.

(Note that your test of the name field is likewise flawed. A name such as "!@#$$%^&()_+-=[]z1234567890" would be *accepted* because of the single "z" in there.)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum