CFFORM doesn't validate dropdown lists / combos even though required="true"
The Problem
Using javascript validation on a CFSELECT within a CFFORM on ColdFusion MX
The symptom
If a user doesn't select a value from a drop down list / combo then no validation occurs
The scenario
When using CFFORM to validate form fields, even though the validate="true" has been specified within the CFFORM, it fails to catch the fact that a value from the combo hasn't been chosen.
In the example below, if the user doesn't select either Male or Female from the drop down list, when you click the submit button the form will not be validated and the form will be submitted with a blank value in the form field specified in the CFSELECT.
<cfselect name="gender" required="yes" message="Select you gender">
<option value="">- Choose -</option>
<option value="M">Male</option>
<option value="F">Female</option>
</cfselect>
<br />
<cfinput type="submit" name="go" value="Submit form">
</cfform>
The fix
To fix this problem you need to edit /CFIDE/scripts/cfform.js and add a tiny amount of extra code. NOTE: If you are in a hosted environment, you can use the scriptSrc parameter within the CFFORM tag. <cfform action="postform.cfm" scriptSrc="[your script directory here]"> This will allow you to upload this fix without your ISP having to modify their ColdFusion installation. Additionally, when they apply ColdFusion updates or hot fixes they changes may be overwritten.
Do a search in the source code for obj.options[i].selected - This should be around about line 78 (based on ColdFusion 7 - Version 8 is at line 57). You then need to replace the value you just searched for with the following:-
ColdFusion 7 instructions
Version 7 code to insert:-
if (obj.options[i].selected && obj.options[i].value != '')
Before:-
{
for (i=0; i < obj.length; i++)
{
if (obj.options[i].selected)
return true;
}
return false;
}
After:- (VERSION 7)
{
for (i=0; i < obj.length; i++)
{
if (obj.options[i].selected && obj.options[i].value != '')
return true;
}
return false;
}
ColdFusion 8 instructions:-
Version 8 code to insert:-
if (b.options[i].selected && b.options[i].value != '')
Before:-
}else{
if(_c=="SELECT"){
for(i=0;i<_b.length;i++){
if(_b.options[i].selected){
return true;
}
After:- (VERSION 8)
}else{
if(_c=="SELECT"){
for(i=0;i<_b.length;i++){
if (_b.options[i].selected && _b.options[i].value != '') {
return true;
}
Key phrases:-
- CFFORM validation
- CFSELECT
Applies to / Tested on:-
- ColdFusion MX7
- ColdFusion 8
