cooking, programming and everyday life xrado

Wednesday, August 13, 2008

javascript form validator with combining rule set

This is actually an old script i made about two years ago. I got the idea form the style classes combining. I thought it would bi nice to have ability to combine some common rules like classes. Instead of class that is used for styles i added new attribute "valid" to each form element that have to be validated. Background colour has shown to be the best choice for error indicator (.fail class), because border style can't be applied to all form element at least in old browsers (like IE).

VALIDATE FUNCTION:
function validate(form) {
	var send = true;
	var f,fl,vl,vll,op,opl,pat;
	for(f = 0, fl = form.length; f < fl; f++) {
		if(form[f].className.match('fail')) form[f].className = form[f].className.replace(/fail+/gi,'');
		if(form[f].type=='checkbox') form[f].parentNode.className = form[f].parentNode.className.replace(/fail+/gi,'');
		if(form[f].getAttribute('valid')) {
			var valid = form[f].getAttribute('valid').split(" ");
			for(vl = 0, vll = valid.length; vl < vll; vl++) {
				var check = valid[vl].split("-");
				switch(check[0]) {
					case 'req': if(!form[f].value.length) { form[f].className +=' fail'; send = false; } break;
					case 'minlen': if(form[f].value.length < check[1]) { form[f].className +=' fail'; send = false; } break;
					case 'maxlen': if(form[f].value.length > check[1]) { form[f].className +=' fail'; send = false; } break;
					...rules
				}
			}
		}
	}
	return send;
}
On submit event triggers validate function which goes trough all form elements and checks valid attribute. If one or more rules are not true, form element gets class .fail which indicates invalid value. Some rules also takes argument via rule-arg syntax. For instance minlen-5 states for minimum string length 5 chars.

RULES
req required ( length > 0 )
minlen-x minimum lenght
maxlen-x maximum lenght
len-x fixed lenght
max maximum numeric value
min minimum numeric value
num numeric
notnum not numeric
nosp no spaces
alp alphabetic
alpnum alphanumeric
date date (eu formating)
email valid email
money money (numeric including ,.)
checked is checked (for checkbox )
selected is selected (for selectbox )
ip ip address

This are some rules i already defined, but you can easily extended it with your own.

USAGE
<html>
<head>
	<script type="text/javascript" src="js/validate.js"></script>
	<style> .fail { background: #DF5353; } </style>
</head>
<body>

<form action="" method="post" onsubmit="return validate(this)">
<table>
	<tr>
		<td width="100">name</td>
		<td><input name="name" valid="req min-5 alp" type="text"></td>
	</tr>
	<tr>
		<td width="100">number</td>
		<td><input name="name" valid="num" type="text"></td>
	</tr>
	<tr>
		<td>check</td>
		<td><input name="true" valid="checked" type="checkbox"></td>
	</tr>
	<tr>
		<td>fruit</td>
		<td>
			<select name="fruit" valid="selected">
				<option></option>
				<option>apple</option>
				<option>bannan</option>
			</select>
		</td>
	</tr>
	<tr>
		<td></td>
		<td><input value="submit" type="submit"></td>
	</tr>
</table>
</form>
	
</body>
</html>
If we look first field example valid has "req min-5 alp", this means that field is required to bi filled, with at least 5 characters that are alphabetic. If all those rules are true field value is valid.

DEMO

I like this script a lot. Its small and gives you easy client side form validation ( don't forget about server side ). It can sure be improved, with like error messages, but I'll leave that up to you. I like it simple.

Download: source
COMMENTS ARE DISABLED