form validation

Ketan Jetty
enthusiasm for technology

form validation

How to use the form validation code function
Note: you will need to use jquery or if you don't want to use jquery you can write a custom function in body onload and invoke the "formObject.enhanceRequiredFields()" function in that.

Click here to see a working demo.

How to use CFTurbine Form Validation script in your code
<script src="jquery.js" type="text/javascript"></script>
<script src="cftValidatorMin.js" type="text/javascript"></script>
<script type="text/javascript">
	/* validators array keys and meaning
		i : id - should be the ID of the element to validate
		t : title - text that need be displayed in the alert
		vs : validations array
		v : validation - value from the list of validation supported eg. isRequired
		m : message - custome message to display on validation failure
		p : parameter - addtional parameter to control the requited field bar 
		    and for isMask RegExp
	*/

	$(document).ready(function(){
		validatorArray = 
		[
			{"i":"first_name","t":"First Name","vs":[{"v":"isRequired"}]},
			{"i":"last_name","t":"Last Name","vs":[{"v":"isRequired",
												    "m":"surname name in upper case",
													"p":"blue"},
												   {"v":"isAlphaUpper"}
												  ]},
			{"i":"username","t":"username","vs":[{"v":"isMask","p":"aA9-x"}]}
		];
		
		//enhance required fields
		formObject.enhanceRequiredFields();
	});
</script>

<body>
	<form id="formSample" name="formSample" action="someAction.cfm" method="POST" onsubmit="return formObject.validate(this);">
		First Name: 
		<input type="text" id="first_name" name="first_name" value=""maxlength="50" style="border:1px solid grey" /> <br/ >
		Last Name:  
		<input type="text" id="last_name" name="last_name" value="" maxlength="50" style="border:1px solid grey" /> <br/ >
		Password:   
		<input type="password" id="passwd" name="passwd" value="" maxlength="50" style="border:1px solid grey" /> <br/ >
		Username:   
		<input type="text" id="username" name="username" value="" maxlength="50" style="border:1px solid grey" /> <br/ >
		<input type="submit" id="btn_submit" name="submit" value="Submit" />		
	</form>
</body>

validations supported
isRequiredcheck for required data
isNumeric checks if the input data is numeric data
isPositiveNumeric check for numeric characters eg. 1, 1.2, 1.34, .2
isInteger check for integer characters
isPositiveInteger check for positive integers
isAlphaNumeric check for alphanumeric character
isAlpha check for alpha characters
isAlphaLower check for alpha characters lower case
isAlphaUpper check for alpha characters upper case
isEmail check for valid email id
isMonth check for valid month xx (01 - 12)
isYear check for valid year for xxxx
isNotPastDate check for date GTE today - epxected format 31/12/2007 or 12/2007 or 2007
isNotPastDateUS check for date GTE today - epxected format 12/31/2007 or 12/2007 or 2007
isPhoneUS check for US phone format 999 999 9999 or 999-999-9999
isZipUS check for zip code in 5 digit format or zip+4 format 99999 or 99999-9999
isZipCANADA check for zip code validation for CANADA - A1B2C3 or A1B 2C3
isZipUSCANADA check for zip code validation for US, CANADA: 99999 or 99999-9999 or A1B2C3 or A1B 2C3
isGTZero check for number value greater than zero, rounded value should be a minimum 0.01
isCreditCard check for valid credit card number
isRegEx validates the field input against a RegExp
isMask checks if the field input adheres to a specific format
a - for alpha lower, A for alpha upper, x for alphanumeric, 9 for integer, - for dash[-]

support functions
highlightField highlights a field that fails validation
resetHighlightFields resets all highlighted fields
enhanceRequiredFields provides the left 5px bar for easy identification of a required field

private functions
_RETrim for RegExp string formatting

CFTurbine Form Validation code
/*
 * CFTurbine Form Validation
 * http://cfturbine.com
 * Copyright (c) 2009 Ketan Jetty, Anang Phatak
 * Version: 1.0
 * freeware
 */

<script src="jquery.js" type="text/javascript"></script>
<script src="cftValidatorMin.js" type="text/javascript"></script>
<script type="text/javascript">
	$(document).ready(function(){
		validatorArray = 
		[
			{"i":"first_name","t":"First Name","vs":[{"v":"isRequired"}]},
			{"i":"last_name","t":"Last Name","vs":[{"v":"isRequired","m":"Do not forget the last name ... custom message.","p":"blue"},
											 {"v":"isAlphaUpper"}
											]},
			{"i":"username","t":"Mask Validation","vs":[{"v":"isMask","p":"aA9-x"}]}
		];
		
		//enhance required fields
		formObject.enhanceRequiredFields();
	});
</script>

String.prototype.trim = function(){
	return this.replace(/^\s+|\s+$/g,'');
};

formObject = {
	validate:function(formObjId){
		var formObj = document.getElementById(formObjId);
		var fvArray = validatorArray;
		var stdErrorMessage = {
			"isNumeric":"Please enter numeric data.",
			"isPositiveNumeric":"Please enter a positive numeric data.",
			"isInteger":"please enter integer values.",
			"isPositiveInteger":"please enter positive integer values.",
			"isAlphaNumeric":"Please enter alphanumeric data.",
			"isAlpha":"Please enter alpha data.",
			"isAlphaLower":"Please enter lower case alpha characters",
			"isAlphaUpper":"Please enter upper case alpha characters",
			"isEmail":"Please enter a valid email id.",
			"isMonth":"Please enter a valid month.",
			"isYear":"Please enter a valid year.",
			"isNotPastDate":"Please enter a valid date (today or future date).",
			"isPhoneUS":"Please enter a valid US phone number.",
			"isZipUS":"Please enter a valid US Zip.",
			"isZipCANADA":"Please enter a valid Canada Zip.",
			"isZipUSCANADA":"Please enter a valid US or Canada Zip.",
			"isGTZero":"Please enter a value grater than zero.",
			"isCreditCard":"Please enter a valid credit card number."
		};
		
		for(var i=0;i<fvArray.length;i++){
			var fvRecord = fvArray[i];
			var fvID = fvRecord.i.trim();
			var fvTITLE = fvRecord.t.trim();
			var fvVALIDATIONS = fvRecord.vs;
			var formElement = document.getElementById(fvID);
			
			for(var j=0;j<fvVALIDATIONS.length;j++){
				var curValidator = '';
				var curMessage = '';
				var curParam = '';
				var fvObj = fvVALIDATIONS[j];
				
				if(fvObj.v! = undefined){curValidator = fvObj.v.trim();}
				if(fvObj.m! = undefined){curMessage = fvObj.m.trim();}
				if(fvObj.p! = undefined){curParam = fvObj.p.trim();}
				
				if(curMessage.length == 0){
					curMessage = 'Please enter a valid input.';
					if(stdErrorMessage[curValidator]! = undefined){
						curMessage = stdErrorMessage[curValidator].trim();
					}
				}
				
				if(curValidator.length>0 && formObject[curValidator]! = undefined){
					if(curValidator == 'isRequired'){
						if(!formObject.isRequired(formElement.value.trim())){
							if(curMessage == 'Please enter a valid input.'){
								curMessage = 'This is a required field.';
							}
							alert('ERROR - Validation failed.\n\nTitle: '+fvTITLE+'\nValue: '+formElement.value+'\n\n'+curMessage);
							formObject.highlightField(formElement);
							return false;}
						}else if(formElement.value.trim().length>0){
							if(curValidator == 'isRegEx'){
								if(!formObject.isRegEx(curParam,formElement.value.trim())){
									alert('ERROR - Validation failed.\n\nTitle: '+fvTITLE+'\nValue: '+formElement.value+'\n\n'+curMessage);
									formObject.highlightField(formElement);
									return false;
								}
							} else if(curValidator == 'isMask'){
								if(!formObject.isMask(curParam,formElement.value.trim())){
									alert('ERROR - Validation failed:\n\nTitle: '+fvTITLE+'\nValue: '+formElement.value+'\n\n'+curMessage+'\nInput format should be similar to: '+curParam);
									formObject.highlightField(formElement);
									return false;
								}
							} else {
								if(!formObject[curValidator](formElement.value.trim())){
									alert('ERROR - Validation failed.\n\nTitle: '+fvTITLE+'\nValue: '+formElement.value+'\n\n'+curMessage);
									formObject.highlightField(formElement);
									return false;
								}
							}
						}
					}else{
						alert('Validation type '+curValidator+' is not defined.\nValidation is not be applied.');
					}
				}
			}
			return true;
		},
		
		_RETrim:function(strValue){
			strValue = strValue.trim();
			if(strValue.indexOf('/') == 0){
				strValue = strValue.substring(1);
			}
			if(strValue.charAt(strValue.length-1) == '/'){
				strValue = strValue.substring(0,strValue.length-1);
			}
			return strValue;
		},
		
		isRequired:function(strValue){
			if(strValue.trim().length == 0){
				return false;
			}
			return true;
		},
		
		isNumeric:function(strValue){
			var objRE = /(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/;
			return objRE.test(strValue);
		},
		
		isPositiveNumeric:function(strValue){
			var objRE = /(^\d\d*\.\d*$)|(^\d\d*$)|(^\.\d\d*$)/;
			return objRE.test(strValue);
		},
		
		isInteger:function(strValue){
			var objRE = /(^-?\d\d*$)/;return objRE.test(strValue);
		},
		
		isPositiveInteger:function(strValue){
			var objRE = /(^\d+$)/;
			return objRE.test(strValue);
		},
		
		isAlphaNumeric:function(strValue){
			var objRE = /(^[a-zA-Z0-9 ]+$)/;
			return objRE.test(strValue);
		},
		
		isAlpha:function(strValue){
			var objRE = /(^[a-zA-Z ]+$)/;
			return objRE.test(strValue);
		},
		
		isAlphaLower:function(strValue){
			var objRE = /(^[a-z ]+$)/;
			return objRE.test(strValue);
		},
		
		isAlphaUpper:function(strValue){
			var objRE = /(^[A-Z ]+$)/;
			return objRE.test(strValue);
		},
		
		isEmail:function(strValue){
			var objRE = /(^[\w\.-]+(\+[\w-]*)?@([\w-]+\.)+[\w-]+$)/;
			return objRE.test(strValue);
		},
		
		isMonth:function(strValue){
			var objRE = /(^0[1-9]|1[0-2]$)/;
			return objRE.test(strValue);
		},
		
		isYear:function(strValue){
			var objRE = /(^[1-2]\d{3}$)/;
			return objRE.test(strValue);
		},
		
		isNotPastDate:function(strValue){
			var now = new Date();
			var curDate = now.getDate();
			var curMonth = now.getMonth()+1;
			var curYear = now.getYear();
			strValue = strValue.split('-').join('/');
			var strDate = strValue.split('/');
			
			if(strDate.length == 1){
				if(strDate[0]<curYear){
					return false;
				}
			}else if(strDate.length == 2){
				if(strDate[0]<curMonth||strDate[1]<curYear){
					return false;
				}
			}else if(strDate.length == 3){
				if(strDate[0]<curDate||strDate[1]<curMonth||strDate[2]<curYear){
					return false;
				}
			}
			return true
		},
		
		isNotPastDateUS:function(strValue){
			var now = new Date();
			var curDate = now.getDate();
			var curMonth = now.getMonth()+1;
			var curYear = now.getYear();
			strValue = strValue.split('-').join('/');
			var strDate = strValue.split('/');
			
			if(strDate.length == 1){
				if(strDate[0]<curYear){
					return false;
				}
			}else if(strDate.length == 2){
				if(strDate[0]<curMonth||strDate[1]<curYear){
					return false;
				}
			}else if(strDate.length == 3){
				if(strDate[0]<curMonth||strDate[1]<curDate||strDate[2]<curYear){
				return false;
				}
			}
			return true;
		},
		
		isPhoneUS:function(strValue){
			var objRE = /^[1-9]\d{2}\s*-?\s*\d{3}\s*-?\s*\d{4}$/;
			return objRE.test(strValue);
		},
		
		isZipUS:function(strValue){
			var objRE = /(^\d{5}$)|(^\d{5}-\d{4}$)/;
			return objRE.test(strValue);
		},
		
		isZipCANADA:function(strValue){
			var objRE = /(^[a-zA-Z][0-9][a-zA-Z]\s*[0-9][a-zA-Z][0-9]$)/;
			return objRE.test(strValue);
		},
		
		isZipUSCANADA:function(strValue){
			var objRE = /(^\d{5}$)|(^\d{5}-\d{4}$)|(^[a-zA-Z][0-9][a-zA-Z]\s*[0-9][a-zA-Z][0-9]$)/;
			return objRE.test(strValue);
		},
		
		isGTZero:function(strValue){if(parseFloat(strValue)<0.01){
			return false;
		}
		
		return true;
	},

	isCreditCard:function(strValue){
		//mod10 algorithm
		strValue = strValue.split('-').join('');
		strValue = strValue.split(' ').join('');
		
		if(strValue.length<13){
			return false;
		}

		var objRE = '';
		var charOne = strValue.charAt(0);
		var charTwo = strValue.charAt(1);
		
		if(charOne == 3){
			if(strValue.length == 15&&(charTwo == 4||charTwo == 7)){
				objRE = /^3[4,7]\d{13}$/;
			}else if(strValue.length == 14&&(charTwo == 0||charTwo == 6||charTwo == 8)){
				objRE = /^3[0,6,8]\d{12}$/;
			}
		}else if(charOne == 4&&strValue.length == 16){
			objRE = /^4\d{3}-?\d{4}-?\d{4}-?\d{4}$/;
		}else if(charOne == 5&&charTwo>0&&charTwo<6&&strValue.length == 16){
			objRE = /^5[1-5]\d{2}-?\d{4}-?\d{4}-?\d{4}$/;
		}else if(charOne == 6&&charTwo == 0&&strValue.length == 16){
			objRE = /^6011-?\d{4}-?\d{4}-?\d{4}$/;
		}
		
		if(!objRE.test(strValue)){
			return false;
		}
		
		var checksum = 0;
		
		for(var i = (2-(strValue.length%2));i< = strValue.length;i+ = 2){
			checksum+ = parseInt(strValue.charAt(i-1));
		}
		
		for(var i = (strValue.length%2)+1;i<strValue.length;i+ = 2){
			var digit = parseInt(strValue.charAt(i-1))*2;
			
			if(digit<10){
				checksum+ = digit;
			}else{
				checksum+ = (digit-9);
			}
		}
		
		if((checksum%10) == 0){
			return true;
		}
		
		return false;
	},

	isRegEx:function(strRE,strValue){
		return new RegExp(formObject._RETrim(strRE)).test(strValue);
	},
	
	isMask:function(strMask,strValue){
		if(strMask.length! = strValue.length){
			return false;
		}
		
		for(var i = 0;i<strMask.length;i++){
			var cMask = strMask.charAt(i);
			var cValue = strValue.charAt(i);
			
			switch(cMask){
				case'a':
					if(!formObject.isAlphaLower(cValue)){
						return false;
					}
					break;
				case'A':
					if(!formObject.isAlphaUpper(cValue)){
						return false;
					}
					break;
				case'9':
					if(!formObject.isInteger(cValue)){
						return false;
					}
					break;
				case'x':
					if(!formObject.isAlphaNumeric(cValue)){
						return false;
					}
					break;
				case'-':
					if(cValue! = '-'){
						return false;
					}
					break;
			}
		}
		
		return true;
	},
	
	resetHighlightFields:function(){
		var fvArray = validatorArray;
		
		for(var i = 0;i<fvArray.length;i++){
			var fvRecord = fvArray[i];
			var fvID = fvRecord.i.trim();
			var formElement = document.getElementById(fvID);
			
			if(formElement.style.borderColor.trim().indexOf('ff4500')>-1||formElement.style.borderColor.trim().indexOf('rgb(255, 69, 0)')>-1){
				formElement.style.borderColor = '999999';
			}
		}
	},
	
	highlightField:function(formElement){
		formObject.resetHighlightFields();
		formElement.style.borderColor = 'ff4500';
		formElement.focus();
	},
		
	enhanceRequiredFields:function(){
		var fvArray = validatorArray;
		
		for(var i = 0;i<fvArray.length;i++){
			var fvRecord = fvArray[i];
			var fvID = fvRecord.i.trim();
			var fvVALIDATIONS = fvRecord.vs;
			var formElement = document.getElementById(fvID);
			
			for(var j in fvVALIDATIONS){
				var curValidator = '';
				var curParam = '999999';
				var fvObj = fvVALIDATIONS[j];

				if(fvObj.v! = undefined){
					curValidator = fvObj.v.trim();
				}
				
				if(fvObj.p! = undefined){
					curParam = fvObj.p.trim();
				}
				
				if(curValidator.length>0&&curValidator == 'isRequired'&&curParam.length>0){
					formElement.style.borderLeft = 'solid 4px';
					formElement.style.borderLeftColor = curParam;
					break;
				}
			}
		}
	}
};

Download cftValidatorMin.js

coldfusion


CF Quick Reference


Ginger CMS
the future of cms, a simple, easy and intutive content management system ... more


CFTurbine
cf prototyping engine, generates boilerplate code and ... more


Jrun monitor
monitor and timely auto-restart to avoid Jrun hang ... more


Inheritance Config.
uses OOPs inheritance to create configuration file ... more


Real Estate App.
complete real estate application using data from MLS ... more


Search Engine Lite
create your own search engine for your web site ... more