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.
<!-- 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; }
function Button1_onclick() { var v = document.all("txtPositiveInteger").value; alert(isPositiveInteger(v)); } //--> </script> </head> <body> <formid="form1"> Enter Positive Integer:<inputtype="text"id="txtPositiveInteger" NAME="txtPositiveInteger"><inputtype="button"value="Validate"id="Button1" name="Button1"onclick="return Button1_onclick()"> </form> </body> </html>
Within the above code, I mainly created a simple text box and a button. The textbox is named “txtPositiveInteger” and the button is named “Button1”. The button is defined with an “onclick” event which calls a JavaScript function, “Button1_onclick”, which is defined as follows:
function Button1_onclick() { var v = document.all("txtPositiveInteger").value; alert(isPositiveInteger(v)); }
The above function defines a variable “v”, which is assigned with a value available (or typed) in the textbox “txtPositiveInteger”. The same variable is passed as a parameter to another JavaScript function, “isPositiveInteger” (which is defined as follows). The value returned by the function “isPositiveInteger” is finally displayed in the form of a message box, using an “alert” statement. Now, let us look into the “isPositiveInteger” 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; }
The above function simply accepts any value (as a parameter value) into the variable “val”. The first “if” statement in the function “isPositiveInteger” simply checks for “null”. The second “if” statement in the same function counts the number of characters available. If no characters are found, it returns “false”.
If any characters are found, we go through each character (using a “for” loop) and check whether the character is NOT within the range of “0” through “9” (based on ASCII). If any character is found, we return false. Finally, we return “true” if no other character apart from digits is found.