long story short, i was trying to validate a phone field. ive added
the isNaN
and parseInt
for checking the " "
in the field but that said
This below never validates to true..what am i missing?
if(isNaN(parseInt(phone))){
error.text("Sorry but this phone field requires numbers only");
return false;
} else {
return true;
}
it always fails...it never reads true even when i enter a number in the field and submit. i always get the error mssg.
EDIT: I am testing input values from a form, phone
is the name of the field.
The parseInt method parses a value as a string and returns the first integer. A radix parameter specifies the number system to use: 2 = binary, 8 = octal, 10 = decimal, 16 = hexadecimal. If radix is omitted, JavaScript assumes radix 10. If the value begins with "0x", JavaScript assumes radix 16.
The main purpose of using the parseInt function is to extract a number from a string. This turns the returned value to an actual number. In the example above, 3 is a string and not an actual number.
Various ways to coerse JS strings to numbers, and their consequences:
(source: phrogz.net)
I personally use *1
as it is short to type, but still stands out (unlike the unary +), and either gives me what the user typed or fails completely. I only use parseInt()
when I know that there will be non-numeric content at the end to ignore, or when I need to parse a non-base-10 string.
Edit: Based on your comment, if using phone.val()
fixed it then
Whenever you do var foo = $('…');
then the foo
variable references a jQuery object of one or more elements. You can get the first actual DOM element from this via var fooEl = foo[0];
or var fooEl = foo.get(0);
…but even then you still have a DOM element and not a particular property of that.
For form inputs, you need to get the .value
from the DOM element, which is what the jQuery .val()
method does.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With