JavaScript Code

JavaScript: Universal Form Checker

I built this function so that I'd never have to configure form checking again. Now I just include this script on any form page, and it handles all the checking for me.

function checkForm( f ) { //June 23, 2003
// loops through each element in the specified form ( f ), and if element is suffixed by '_required',
// function checks if there is valid data.
// If all is well submit form otherwise alert user which elements need to be filled.
var strMessage = 'Please fix the following:\n\n';
var objTemp;
var strName = "
var boolIsValid = true;
for ( var i = 0; i < f.elements.length; i++ ) { objTemp = f.elements[i]; strName = objTemp.name //alert(strName) if ( strName.substr( strName.length - 9 ) == '_required' ) { // first see if it's required //if required, parse the name //strName = strName.replace( /data_/, '' ); strName = strName.replace( /_required/, '' ); strName = strName.replace( /_/g, ' ' ); strName = strName.toLowerCase(); if ( objTemp.value == '' ) { boolIsValid = false; strMessage += strName + ' is empty\n'; } else if ( objTemp.type == 'radio' ) { boolIsValid = false; for ( var j = 0; j < objTemp.length; j++ ) { if ( objTemp[j].checked ) { boolIsValid = true; break; } } } if ( strName.indexOf( 'first name' ) != -1 && objTemp.value == 'First' ) { boolIsValid = false; strMessage += strName + ' is invalid\n'; } else if ( strName.indexOf( 'last name' ) != -1 && objTemp.value == 'Last' ) { boolIsValid = false; strMessage += strName + ' is invalid\n'; } else if ( strName.indexOf( 'email' ) != -1 && ( objTemp.value.indexOf( '@' ) == -1 || objTemp.value.indexOf( '.' ) == -1 ) ) { boolIsValid = false; strMessage += strName + ' is invalid\n'; } else if ( strName == 'verify password' && ( objTemp.value != f.data_password_required.value ) ) { boolIsValid = false; strMessage += 'Passwords do not match!\n'; } } } if ( boolIsValid == true ) { return true; } else { alert( strMessage ); return false; } } [/code]

Share

Leave a Reply

Your email address will not be published. Required fields are marked *

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image