Wednesday, July 22, 2009

CFSELECT Validation

There is a very easy way to force a selection on a select box.
All you have to do is edit a tiny bit of code.

If you have access to your CFIDE/scripts folder, just edit your cfform.js file directly. But if you are on a shared host, there is a simple fix.

First copy your cfform.js file to anywhere on your site. We'll copy it to our webroot/js folder for this example.

Then, if you are using CF8 edit line 59 from this:


if(_b.options[i].selected) {



To this:


if(_b.options[i].selected && _b.options[i].value != "") {



Then you simply have to point your form to use the new cfform.js file. You do that very easily with the scriptsrc attribute of the cfform tag, like this:


<cfform scriptsrc="webroot/js/cfform.js">



Finally, on the cfselect boxes you want to validate, you add a blank option and make the cfselect required.


<cfselect name="mySelect" query="myQuery" display="myField" value="myID" queryPosition="below" required="yes" message="You must choose this field.">
<option value="" selected><option>
</cfselect>



And that's it!
It took me some digging to figure this out, but now that I found it it's very simple and straightforward.