Developing a simple validation library in JavaScript
(Page 1 of 5 )
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.
You can directly test any or all of the examples in this series simply by copying and pasting the entire code (of each section) into any text file with the extension .HTM, and opening it using a browser.
Validations for blanks, empty strings, nulls etc.
Now, let us try to develop a simple script (JavaScript) to validate blanks, empty strings, nulls, and so on. Take a look at the following code:
<html>
<head>
<script id=clientEventHandlersJS language=javascript>
<!--
function isBlank(val){
if(val==null){return true;}
if(val.length==0) {return true;}
return false;
}
function Button1_onclick() {
var v = document.all("txtName").value;
alert(isBlank(v));
}
//-->
</script>
</head>
<body>
<form id="form1">
Enter name:<input type="text" id="txtName"> <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 “txtName” and the button is named “Button1”. The button is defined with an “onclick” event, which calls a JavaScript function named “Button1_onclick”, which is defined as follows:
function Button1_onclick() {
var v = document.all("txtName").value;
alert(isBlank(v));
}
The above function defines a variable “v”, which is assigned with a value available (or typed) in the textbox called “txtName”. The same variable is passed as a parameter to another JavaScript function, “isBlank” (which is defined as follows). The value returned by the function “isBlank” is finally displayed in the form of a message box, using an “alert” statement. Now, let us look into the “isBlank” function.
function isBlank(val){
if(val==null){return true;}
if(val.length==0) {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, it returns “true”. Finally, if none of the “if” statements work, we return “false” (similar to “not blank”).
Next: Validations for spaces, tabs, carriage returns, new line characters etc. >>
More JavaScript Articles
More By Jagadish Chaterjee