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:
';
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
';
} 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
';
} else if ( strName.indexOf( 'last name' ) != -1 && objTemp.value == 'Last' ) {
boolIsValid = false;
strMessage += strName + ' is invalid
';
} else if ( strName.indexOf( 'email' ) != -1 && ( objTemp.value.indexOf( '@' ) == -1 || objTemp.value.indexOf( '.' ) == -1 ) ) {
boolIsValid = false;
strMessage += strName + ' is invalid
';
} else if ( strName == 'verify password' && ( objTemp.value != f.data_password_required.value ) ) {
boolIsValid = false;
strMessage += 'Passwords do not match!
';
}
}
}
if ( boolIsValid == true ) {
return true;
} else {
alert( strMessage );
return false;
}
}
Sign up for our daily email newsletter:
You must log in to post a comment.