Developing a simple validation library in JavaScript: continued
This series of articles mainly lists some of the most commonly used JavaScript functions for client side validation of HTML forms. You can reuse these scripts to inject into server side controls easily.
Developing a simple validation library in JavaScript: continued - Validation for an integer (both positive and negative) (Page 3 of 4 )
In the previous section, we worked on validating a multi-digit number with the following function.
function isPositiveInteger(val){ if(val==null){returnfalse;} if (val.length==0){returnfalse;} for (var i = 0; i < val.length; i++) { var ch = val.charAt(i) if (ch < "0" || ch > "9") { return false } } returntrue; }
Now we need to extend the same function to work with the negative symbol (or hyphen) as well. Let us look at the following code:
<html> <head> <scriptid="clientEventHandlersJS"language="javascript"> <!-- function isInteger(val){ if(val==null){returnfalse;} if (val.length==0){returnfalse;} for (var i = 0; i < val.length; i++) { var ch = val.charAt(i) if (i == 0 && ch == "-") { continue } if (ch < "0" || ch > "9") { return false } } return true }
function Button1_onclick() { var v = document.all("txtInteger").value; alert(isInteger(v)); } //--> </script> </head> <body> <formid="form1"> Enter Integer:<inputtype="text"id="txtInteger"NAME="txtInteger"><inputtype="button"value="Validate"id="Button1" name="Button1"onclick="return Button1_onclick()"> </form> </body> </html>
The new function is defined as follows:
function isInteger(val){ if(val==null){returnfalse;} if (val.length==0){returnfalse;} for (var i = 0; i < val.length; i++) { var ch = val.charAt(i) if (i == 0 && ch == "-") { continue } if (ch < "0" || ch > "9") { return false } } return true }
From the above function, the only extra is the following condition:
if (i == 0 && ch == "-") { continue }
The above “if” condition simply ignores the hyphen symbol, if it is found at the first position (or index with 0). Other than the above modification, the rest of the code should be very familiar.