Link to home
Start Free TrialLog in
Avatar of leestott
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.
Avatar of Michel Plungjan
Michel Plungjan
Flag of Denmark image

And Why no built-in functions?
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)) ==-1) return false
  }
  return true
}
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
}
ASKER CERTIFIED SOLUTION
Avatar of GwynforWeb
GwynforWeb
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Riiight... RegExps are less compatible than isNaN - ;)
Avatar of Zontar
Zontar

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?
"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.
Avatar of leestott

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
You did not ask for a regexp... If you had I would not have given you the suggestion I gave.