Andy Jarrett // Code. Develop. Create.

Model Glue Form Validation

I've been working on a app with a couple of forms and wanted to break the validation rules into different group of rules e.g.

1. Rules for address
2. Rules for personal information
3. Rules specific per form.

What this allows me to do is is per validation call in the controller just use the validators i need.

How I am doing it:

1. Create a controller called validator.cfc
2. Create you validation.cfc's i.e.
  1. validator_Personal.cfc
  2. validator_address.cfc
  3. validator_other.cfc
Your validation cfc's should look like this:<cfcomponent> <cffunction name="validate" returnType="ModelGlue.Util.ValidationErrorCollection"> <cfargument name="formFields"> <cfset var val = createObject("component", "ModelGlue.Util.ValidationErrorCollection").init() /> <cfif structKeyExists(formFields, "address1") AND not len(trim(formFields.address1))> <cfset val.addError("address1", "Please enter the first line of your address.") /> </cfif> </cffunction></cfcomponent>

3. In validator controller create a listener which has calls the validator objects e.g.

<cffunction name="validateDetails" access="Public" returnType="ModelGlue.Core.Event" output="false" hint="I am an event handler."> <cfargument name="event" type="ModelGlue.Core.Event" required="true"> <cfset variables.validatePersonal = createObject("component", "model.validator_Personal") > <cfset variables.validateAddress = createObject("component", "model.validator_address")> <cfset valReq = variables.validatePersonal.validate(arguments.event.getAllValues()) /> <cfset valAddress = variables.validateAddress.validate(arguments.event.getAllValues()) /> <cfset valReq.merge(valAddress) /> <cfif valReq.hasErrors()> <cfset arguments.event.addResult("inValid") /> <cfset arguments.event.setValue("validation", valReq.getErrors()) /> <cfelse> <cfset arguments.event.addResult("valid") /> </cfif> <cfreturn arguments.event /></cffunction>

4. To finish it off, in your form you need the usual viewState calls

<cfset val = viewState.getValue("validation", structNew()) />

I’m here, learning and working away. If you liked this content and want to keep me going, consider buying me a coffee. Your support keeps this site running and the coffee brewing! ☕️