Free code! (Server Side Validation...)

Yay! Free code! The only thing better than free code? Free Beer! Since I can't tap a keg on my blog, I'll give you all some free code.
I got Hal Helms' occasional newsletter in which he describes his newly created method of server-side validation.
I didn't realize there were no good examples out there in the ColdFusion community. So here's how I do it, along with the code. Whether you thinks it's good or not, well I guess that's up for debate.
I've got three parts:
(1) A CFC to handle the actual validation
(2) A custom tag to show the error messages, if any
(3) Some simple <cfscript> to set up what needs to be validated
Let's look at some code:
variables.rf = ArrayNew(1);
variables.rf[1] = StructNew();
variables.rf[1].fieldName = 'Photo_Name';
variables.rf[1].required = true;
variables.rf[1].displayName = 'Title';
variables.rf[1].validate = '';
variables.rf[2] = StructNew();
variables.rf[2].fieldName = 'Photo_File';
variables.rf[2].required = true;
variables.rf[2].displayName = 'photo to upload';
variables.rf[2].validate = '';
variables.invalid = application.objFormValidate.validate(rf=variables.rf,form=form);
</cfscript>
This is the <cfscript> that's setting up what needs to be validated. I'm using an array of structures to determine what needs validated and how. The first key in the structure, "fieldName", is the actual name of the formfield. The second, "required", is whether or not the field is required. The third, "displayName" is how you want the name of the field displayed in the event that there is a validation error. The last two, "validate" and "validateAttribute" are what you want to validate, for example, length or email would be valid attributes for "validate" and 50 would be valid for "validateAttribute".
Finally, call the "validate" method of the formValidate.cfc and you'll get back an array of structures containing the violations. If there aren't any, you'll get back an empty array. If there are errors, the array is made up of a structure that includes the offending field name and an appropriate error message.
This is still a work in progress, but it's pretty solid for now. I'm working on making "validate" and "validateAttribute" so you can pass in more than one value for each.
I've posted the .cfc and the custom tag I use to display the errors that are returned.
I'd love to have feedback, let me know what you think. And if you want to take it and improve upon it, feel free.
Here's the code: formValidation.zip


There are no comments for this entry.
[Add Comment]