Forum Moderators: open

Message Too Old, No Replies

javascript validation help

         

anhnguyen

8:02 am on Oct 1, 2003 (gmt 0)

10+ Year Member



this is the fuction check with number.
function checkPhoneNumber(stringEntered) {
var stripped = "";
if(stringEntered.search(/(^0-9)+/)) {
stripped = stringEntered.replace(/[\(\)\.\-\ ]/g, '');
} else {
stripped = stringEntered;
}
if(isNaN(parseInt(stripped))) {
return false;
}
return true;
}
when i try to type "dfsdf4" , it return false..should be fine..
when i type like this "3dsdaas" it return true, should be return false.
can u help me with that
thanks

tedster

1:07 am on Oct 2, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



parseInt() converts and returns any number at the beginning of a string. It returns NaN ("not a number") if the string does not BEGIN with a number.

But as you've discovered, parseInt() simply ignores any trailing non-numbers, including spaces. The function parses however many numeric characters may occur at the start of a string, and returns NAN if the string doesn't begin with a number.

What you need to do is cycle through EACH character your "stripped" variable, testing for isNaN().

MonkeeSage

1:44 am on Oct 2, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I'm not sure what you are aiming for, anhnguyen, but it might be simpler to just do one replace operation if you just want to make sure a valid phone number was given.

Example:

function checkPhoneNumber(stringEntered) {  
stringEntered = stringEntered.replace(/[^0-9]/g, '');
if ((stringEntered.length == 7) ¦¦
(stringEntered.length == 10)) {
return true;
}
else {
return false;
}
}

So...

checkPhoneNumber("888-888-8888");

...and...

checkPhoneNumber("888-8888");

will return true, but...

checkPhoneNumber("8a8-8ss-8a88");

...will return false.

Jordan