Shaun Mccran

My digital playground

17
J
A
N
2010

Using Coldfusion to generate JQuery validation scripts

One of the ideas that we have been throwing around the office is creating a platform that will create the form-validation-database cycle automatically. Something akin to ORM, but not. ORM looks good, but we want more control over what is happening.

In this article I am exploring the idea of automatically creating JQuery validation from a simple Coldfusion input. In this case a list of required fields. I'll say up front Ray Camden's blog entry on Jquery Validation (http://www.coldfusionjedi.com/index.cfm/2009/2/10/An-Introduction-to-jQuery-and-Form-Validation-2) has been an invaluable help.

The principle behind this is that you can create a generic validation object routine, and simple provide it with a set data object (list or struct, haven't decided yet) and have it match against a form and validate it. So with that in mind we will create a simple form.

view plain print about
1<form name="form" id="form" method="post" action="index.cfm?inline=#url.inline#">
2
3<label for="name">Name</label><br/>
4<input type="text" name="name" id="name" class="form-field"><p/>
5
6<label for="telephone">Telephone</label><br/>
7<input type="text" name="telephone" id="telephone" class="form-field"><p/>
8
9<label for="email">Email</label><br/>
10<input type="text" name="email" id="email" class="form-field"><p/>
11
12<label for="favouriteSandwhich">Favourite Sandwhich</label><br/>
13<input type="text" name="favouriteSandwhich" id="favouriteSandwhich" class="form-field"><p/>
14
15<input type="submit" name="action" value="Submit">
16
17</form>
As you can see from above, this is a simple form. Next we will include references to the Google code repository for the AJAX library, and out JQuery validation plugin.
view plain print about
1<scr/ipt type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
2<scr/ipt type="text/javascript" src="jquery.validate.pack.js"></script>
Next we have the JQuery script to validate our fields. Firstly we create a list of the fields that are required. By doing this it is incredibly easy to add another required field to the model.
view plain print about
1<cfset variables.requiredList = "name,email">
The next phase of this will probably accept a structure rather than a list, in that way I can combine field lengths and any other custom criteria, rather than merely the fact that it is required. The JQuery validation starts off in exactly the same way as usual, we create a function to catch the validation request, and use the id of the form as the reference. We declare the error container style of "#error". Next we loop over our list inside the "rules:" element. This creates the required rules for each field. I've also added a basic check for the value 'email'. This will create an email validation rule. Next we create custom messages in the "message:" element. Again this catches the email value and adds an appropriate message.
view plain print about
1<scri/pt>
2        $(document).ready(function(){
3            $("#form").validate({
4            
5            errorContainer: "#error",
6            errorLabelContainer: "#error ul",
7            wrapper: "li",
8
9            rules: {
10                <cfoutput>
11                    <cfloop list="#variables.requiredList#" index="variables.index">
12                    #variables.index#: {required: true <cfif findNoCase('email', variables.index, '1')>, email: true</cfif>, minlength: 5},
13                    </cfloop>
14                </cfoutput>
15                    },
16
17            messages: {
18                
19                <cfoutput>
20                    <cfloop list="#variables.requiredList#" index="variables.index">
21                    #variables.index#: {required: "The #variables.index# field is required",
22                    <cfif findNoCase('email', variables.index, '1')> email: "Email addresses are of the form user@host. Please enter a valid email address.",</cfif>
23                     minlength: jQuery.format("You need to use at least {0} characters for your name.")
24                    },
25                    
26                    </cfloop>
27                </cfoutput>
28            
29                     }
30                                }
31            );
32        });
33        </script>
Lastly we can create a style for the #error container we declared above.
view plain print about
1<style>
2/* Error handling styles */
3#error {-moz-background-clip:border;
4        -moz-background-inline-policy:continuous;
5        -moz-background-origin:padding;
6        background:#FFE7DF;
7        background-position: 5px 8px;
8        border: #FF3F00 solid 1px;
9        color:#440000;
10        margin:10px 0 1em;
11        padding:0px 7px 7px 7px;
12        display:none;
13        width: 90%;}
14
15/* padding for the list */
16#error ul {list-style-type:none; padding: 0px 0px 0px 0px;}
17
18/* padding for the list items */
19#error ul li {padding: 4px 0 2px 16px;}
20
21.error {color: red; list-style-type:none; padding: 0px 0px 0px 0px; width: 198px; color:#440000; background:#FFE7DF;}
22li {list-style-type:none;}    
23.form-field {width: 200px; padding: 0px 0px 0px 0px;}
24</style>

This creates a totally dynamic validation routine - all fed from a list. I think it forms a good basis to build a more dynamic rules driven model, where you can set field lengths as well.

There is an example of the complete code here, along with a variation on the inline or external placing of the validation messages.

Follow this link for a demo of the JQuery validation model.

TweetBacks
Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
Bob Silverberg's Gravatar Dynamically generating client-side validations using metadata in ColdFusion is an excellent idea. It's something that I've been doing for years, and my approach has evolved over time. When I started down this road I quickly realized that it made sense to generate server-side validations as well, as they both rely on the same set of metadata.

Now comes the self-promoting part, for which I apologize, but seeing that you have the same ideas about generating validations I cannot help but mention that I actually released an open source framework awhile ago which addresses these issues.

It's available on Riaforge.org, and more info on it is available at www.validatethis.org. I'd be interested to hear what you think about it.

Cheers,
Bob
# Posted By Bob Silverberg | 19/01/2010 01:47
Shaun Mccran's Gravatar You raise a good point when you say that you are generating the server side validation as well. I am still coding this by hand at present, so I have to watch that the rules are the same.

Thanks for the link, I'll check it out. I have a few ideas about which direction I want to take this, so hopefully your site will provide some inspiration!
# Posted By Shaun Mccran | 21/01/2010 22:16
Back to top