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){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;
}
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>
<script id="clientEventHandlersJS" language="javascript">
<!--
function isInteger(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 (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>
<form id="form1">
Enter Integer:<input type="text" id="txtInteger" NAME="txtInteger"> <input type="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){return false;}
if (val.length==0){return false;}
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.
Next: Validation for a number (both integers and floating point numbers, either positive or negative) >>
More JavaScript Articles
More By Jagadish Chaterjee