johnuk
January 19, 2012, 2:34pm
1
Hi all,
Im creating a postage calc for an Aussie client, and I need to check the input is numeric before I run it through a switch to decide which State/Territory the postcode belongs too (im guessing thats the best idea).
What would be the best way to check the input is numeric/integer before I run a test on it?
Many thanks!
rguy84
January 19, 2012, 3:45pm
2
rguy84
January 19, 2012, 4:06pm
4
You’re welcome, glad it helped.
<script type=“text/javascript”>
function form_input_is_numeric(input){
return !isNaN(input);
}
</script>
That function will pronunce an empty string to be numeric, so without supporting validation its use is inadvisable.
If you’re getting value from a form, you can just use Number() to turn the string value in to a number.
var postcode = Number(form.elements.postcode.value);
or, If you want to ensure that it’s an integer, parseInt() can be used instead.
var postcode = parseInt(form.elements.postcode.value, 10);
paul_wilkins:
If you’re getting value from a form, you can just use Number() to turn the string value in to a number.
var postcode = Number(form.elements.postcode.value);
Number( "" ) == 0
or, If you want to ensure that it’s an integer, parseInt() can be used instead.
var postcode = parseInt(form.elements.postcode.value, 10);
That ensures that it starts with an integer.
parseInt( "1oo", 10) == 1
The most satisfactory solution I’ve seen is to use isFinite combined with parseFloat to eliminate null strings.
return !isNaN( parseFloat( n ) ) && isFinite( n );