Developing a simple validation library in JavaScript: continued - Validation for a positive integer (only digits, no symbols)
(Page 2 of 4 )
In my previous article, we worked on single digit validation with the following function.
function isSingleDigit(val){
if(val==null){return false;}
if (val.length==0 || val.length>1){return false;}
if ((val.charAt(0) >= "0") && (val.charAt(0) <= "9")) {return true;}
return false;
}
Now we need to extend the same function to work with more than one digit. Let us look at the following code:
<html>
<head>
<script id="clientEventHandlersJS" language="javascript">
<!--
function isPositiveInteger(val){
if(val==null){return false;}
if (val.length==0){return false;}
for (var i = 0; i < val.length; i++) {
var ch = val.charAt(i)
if (ch < "0" || ch > "9") {
return false
}
}
return true;
}
function Button1_onclick() {
var v = document.all("txtPositiveInteger").value;
alert(isPositiveInteger(v));
}
//-->
</script>
</head>
<body>
<form id="form1">
Enter Positive Integer:<input type="text" id="txtPositiveInteger"
NAME="txtPositiveInteger"> <input type="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){return false;}
if (val.length==0){return false;}
for (var i = 0; i < val.length; i++) {
var ch = val.charAt(i)
if (ch < "0" || ch > "9") {
return false
}
}
return true;
}
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.
Next: Validation for an integer (both positive and negative) >>
More JavaScript Articles
More By Jagadish Chaterjee