Triggering CFForm Validation When Using Ajax

Published: {ts '2012-07-17 00:00:00'}
Author: Steven Neiland
Site Url: http://www.neiland.net/article/triggering-cfform-validation-when-using-ajax/

Im super busy with work at the moment so this week Im just going to a do a quick 101 post.

Aside: I am not a fan of cfform in general but sometimes you don't get a choice in what technologies you have to work with.

Triggering CFForm Validation With AJAX

Normally when you use the cfform tag ColdFusion triggers its validation javascripts when you click the submit button. However when you use ajax to submit a cfform the trigger event which calls the validation scripts does not execute. So in order to get the validation running again we need to manually add the validation trigger to the ajax submission javascript.

Example: Validation Not Working

Lets take a simple cfform example where clicking the submit button calls an ajax submission function.


The ajax submission code for this form looks like this.

submitForm = function(){ ColdFusion.navigate('updateTask.cfm','resultOP', {callback handler}, {error handler}, 'POST', 'TaskForm'); }

As you can see if we did not use ajax to submit the form the count input field would require an integer value. So lets modify this example to reconnect the validation scripts.

Example: With Validation Working

The first thing we need to do is get a reference to the form. You can do this a couple of different ways but the easiest way is to just pass the reference as a variable in the submitForm call. To do this add "this.form" to the submit form button javascript call.

With the reference passed we can now execute the validation scripts. The way CF generates validation scripts for forms is by creating a validation function for each cfform. The name of this script follows this convention.

_CF_checkFORMNAME(formreference);

So for the above form named "TaskForm" the script name becomes.

_CF_checkTaskForm(formreference);

To put this together we modify the submit form function as follows.

submitForm = function(formreference){ //run the validation rules and get back a true/false value based on success var check = _CF_checkTaskForm(formreference); if (!check) { //if the rules failed then do not submit the form return false; } else { //If checks pass then submit the form via ajax ColdFusion.navigate('updateTask.cfm','resultOP', {callback handler}, {error handler}, 'POST', 'TaskForm'); } }