JavaScript can be used to validate input data in HTML forms before sending off the content to a server. It is one of the most useful utility to help increase usability for the site. In this article we will try to explain how to create a form validation that reacts to submit button.
Form data that typically are checked by a JavaScript could be:
- has the user left required fields empty?
- has the user entered a valid e-mail address?
- has the user entered a valid date?
- has the user entered text in a numeric field?
First we need to create the following trim functions
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
return this.replace(/\s+$/,"");
}
now the validation function:
function form_validate(form_obj) {
var result = false;
var msg = "";
for ( i = 0 ; i < form_obj.elements.length ; i++ ) {
var obj = form_obj.elements[i];
switch ( obj.type ) {
case "text":
case "textarea":
var classnames = obj.className;
classnames = classnames.split(" ");
for ( j = 0 ; j < classnames.length ; j++ ) {
if ( classnames[j] == "require" ) {
if ( obj.value.trim() == "" ) {
msg += "\n"+obj.title;
}
break;
}
}
break;
case "radio":
case "checkbox":
var classnames = obj.className;
classnames = classnames.split(" ");
for ( j = 0 ; j < classnames.length ; j++ ) {
if ( classnames[j] == "require" ) {
var ch_obj = document.getElementsByName(obj.name);
var check = false;
for ( ch_i = 0 ; ch_i < ch_obj.length ; ch_i++ ) {
if ( ch_obj[ch_i].checked ) {
check = true;
break;
}
}
if ( !check ) {
msg += "\n"+obj.title;
}
break;
}
}
break;
}
}
if ( msg.trim().length > 0 ) {
result = false;
alert(msg);
}else
result = true;
return result;
}
To use this function call it on your form’s submit and pass the form object.
To make a required element set its class to “require” and set the related error message in the “title”
Example:
Textbox –
<input type="text" class="require" title="Please type your name" name="first_name" / >
TextArea –
<textarea name="address" class="require" >< / textarea>
Checkbox –
<input type="checkbox" name="ch[]" class="require" title="Please select a category" value="category1" />
<input type="checkbox" name="ch[]" value="category2" / >
Radio button –
< input type="radio" name="rd" class="require" title="Please select a gender" value="male" />
< input type="radio" name="rd" value="female" / >