PDA

View Full Version : regex filters


ShMiL
09-13-2005, 12:03 PM
I run this validation function:

var x = e.phone.value;
var filter = /0(2|3|4|8|9|52|54|57)(\-)?([0-9]{7})/;
if (!filter.test(x)) {
alert('phone error');
e.phone.select();
return false;
}


which suppose to allow prefix (02 or 03 or 04 or 08 or 09 or 052 or 054 or 057), then seperator ("-", or no seperator at all), and then 7 numbers.
the problem is that it works with 8 numbers too (6 and down are declined).

How Come?

NancyJ
09-13-2005, 12:25 PM
Try


var x = e.phone.value;
var filter = /^0(2|3|4|8|9|52|54|57)(\-)?([0-9]{7})$/;
if (!filter.test(x)) {
alert('phone error');
e.phone.select();
return false;
}


The reason you can have 8 or more characters is because the string matches the beginning of your string and ignores the rest. ^specifies that it must match at the beginning of the string and $ at the end specifies that it must match the end of the string, so if you want to find an exact match then you enclose your pattern in ^$ so it must match the beginning and the end of the string...

ShMiL
09-13-2005, 12:54 PM
Thanks alot :))))