Developing a simple validation library in JavaScript - Validation for single digit or single alphabet
(Page 3 of 5 )
Now, let us try to develop a simple script (JavaScript) to validate a single digit. Take a look at the following code:
<html>
<head>
<script id="clientEventHandlersJS" language="javascript">
<!--
function isSingleDigit(val){
if(val==null){return false;}
if (val.length==0 || val.length>1){return false;}
var chars2check="0123456789";
if (chars2check.indexOf(val)!=-1){return true;}
return false;
}
function Button1_onclick() {
var v = document.all("txtDigit").value;
alert(isSingleDigit(v));
}
//-->
</script>
</head>
<body>
<form id="form1">
Enter single digit:<input type="text" id="txtDigit" NAME="txtDigit"> <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 “txtDigit” 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("txtDigit").value;
alert(isSingleDigit(v));
}
The above function defines a variable “v”, which is assigned with a value available (or typed) in the textbox “txtDigit”. The same variable is passed as a parameter to another JavaScript function, “isSingleDigit” (which is defined as follows). The value returned by the function “isSingleDigit” is finally displayed in the form of a message box, using an “alert” statement. Now, let us look into the “isSingleDigit” function.
function isSingleDigit(val){
if(val==null){return false;}
if (val.length==0 || val.length>1){return false;}
var chars2check="0123456789";
if (chars2check.indexOf(val)!=-1){return true;}
return false;
}
The above function simply accepts any value (as a parameter value) into the variable “val”. The first “if” statement in the function “isBlank” simply checks for “null”. The second “if” statement in the same function counts the number of characters available. If no characters are found or if it finds more than one, it returns “false”.
The third “if” statement tries to find the position of the value available in “val” in a set of characters (or string), “0123456789”. The “indexOf” returns “-1” if no value is found during the search.
In a similar fashion, to check for a single alphabet, we can rewrite the above function as follows:
function isSingleAlphabet(val){
if(val==null){return false;}
if (val.length==0 || val.length>1){return false;}
var chars2check="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOP
QRSTUVWXYZ";
if (chars2check.indexOf(val)!=-1){return true;}
return false;
}
Next: Validation for single digit or single alphabet: another way >>
More JavaScript Articles
More By Jagadish Chaterjee