javascript: Checking if required fields have data
Instead of creating multiple Javascript if conditions for every required form field that you have, you can call one function and it will check all of the fields you specified and display an error message if any do not have values.
The function uses a trim( ) function to strip out leading and trailing spaces.
Example HTML/CFML code: Code:
<script language="Javascript">
function trim(thisString){
var newString = thisString;
while (newString.charCodeAt(0) < 33)
{
newString = newString.substring(1,newString.length);
}
while (newString.charCodeAt(newString.length - 1) < 33)
{
newString = newString.substring(0, newString.length - 1);
}
return newString;
}
// Validate that a list of fields contain a value (leading and traling spaces are removed)
// First paramter: the form reference. If your form name is "ServiceForm", then pass "document.ServiceForm"
// Second Parameter: A pipe delimited list of field names (case senastive)
// Third Parameter: A pipe delimited list of field descriptions
//
function ValidateRequiredFields(thisform,Fields,Desc)
{
var tmpVal='';
var FieldArray=new Array();
var DescArray=new Array();
var tmp=0;
// Create array for Field list
tmpVal=Fields;
do
{
tmp=tmpVal.indexOf('|');
if (tmp == -1)
{
if (tmpVal != '')
{
FieldArray[FieldArray.length]=tmpVal;
tmpVal='';
}
} else {
FieldArray[FieldArray.length]=tmpVal.substring(0,tmp);
tmpVal=tmpVal.substring(tmp + 1);
}
}
while (tmpVal != '');
// Create array for Desc list
tmpVal=Desc;
do
{
tmp=tmpVal.indexOf('|');
if (tmp == -1)
{
if (tmpVal != '')
{
DescArray[DescArray.length]=tmpVal;
tmpVal='';
}
} else {
DescArray[DescArray.length]=tmpVal.substring(0,tmp);
tmpVal=tmpVal.substring(tmp + 1);
}
}
while (tmpVal != '');
// Check to see if passed strings are of equal length
if (FieldArray.length != DescArray.length)
{
alert('Fatal error: ValidateRequiredFields - Passed lists do not have the same length');
return false;
}
// Validate fields
for (i=0; i < DescArray.length; i++)
{
eval('tmpVal=thisform.' + FieldArray[i] + '.value');
if (trim(tmpVal) == '')
{
alert(DescArray[i] + ' is required.');
eval('thisform.' + FieldArray[i] + '.focus()');
return false;
}
}
return true;
}
function SubmitForm()
{
if (!ValidateRequiredFields(document.Test,'FirstName|LastName','First Name|Last Name')) return false;
alert('All is okay!');
}
</script>
<form name="Test">
First Name: <input type="Text" name="FirstName" value=""><br>
Last Name: <input type="Text" name="LastName" value=""><br>
<input type="Button" value="Go!" onClick="SubmitForm()">
</form>