leestott
asked on
JavaScript function to validate a text field on a form which is to contain an integer,without using any built functions like IsNaN
I want to write a JavaScript function to validate a text field on a form which is to contain an integer, without using any built functions like IsNaN an so fourth. If the text field contains a valid number then the JavaScript function can return “true”, otherwise it returns “false” as well as displaying a popup error message.
With popup - but still using the built-in indexOf and charAt
function isInteger(str) {
if (!str) return false; // empty
testStr = ""+str
for (i=0;i<testStr.length;i++) {
if (nums.indexOf(str.charAt(i )) ==-1) {
alert(str+' is not a number')
return false
}
}
return true
}
function isInteger(str) {
if (!str) return false; // empty
testStr = ""+str
for (i=0;i<testStr.length;i++)
if (nums.indexOf(str.charAt(i
alert(str+' is not a number')
return false
}
}
return true
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Riiight... RegExps are less compatible than isNaN - ;)
If you're concerned about compatibility, parseInt() is JS 1.0 (NN2+) and isNan() is JS1.1 (NS3+/MSIE3+) whereas regular expressions are JS 1.2 (NS4+/MSIE4+). And parseInt() and isNaN() are much simpler and less resource-intensive.
This isn't a homework assignment, is it?
This isn't a homework assignment, is it?
"regular expressions as used here can be used in many laguages other than javascript" is true as "isNaN is not used in many other languages" , browser compatibility is a different issue.
ASKER
The reason is I have a number of form on our web server which is amount box and what to ensure noone enter number and not intergers such as £100,234 they can only enter a real . the reason for asking for a regex is due to the site mainly being built in asp.net so if I have a regex easily port to vb etc.
Thanks
Thanks
You did not ask for a regexp... If you had I would not have given you the suggestion I gave.
nums = "0123456789"
function isInteger(str) {
if (!str) return false; // empty
testStr = ""+str
for (i=0;i<testStr.length;i++)
if (nums.indexOf(str.charAt(i
}
return true
}