Coldbox - Required Form Fields Plugin »

1

Tags: Railo, Coldbox, Coldfusion

This simple plugin for Coldbox validates required form fields and ensures that they are not blank. It does not validate things like email addresses and telephone numbers. It purely checks that required fields are completed and returns a boolean and simple message to indicate a success or failure.

The component below is the RequiredFields.cfc plugin that can be used within Coldbox.

RequiredFields.cfc

<cfcomponent name="RequiredFields" extends="coldbox.system.plugin" output="false">

    <cffunction name="init" access="public" returntype="RequiredFields" output="false">
        <cfargument name="controller" type="any" required="true">
        <cfset super.Init(arguments.controller) />
        <cfset setpluginName("Required Fields Plugin")>
        <cfset setpluginVersion("1.0")>
        <cfset setpluginDescription("This plugin checks for form validations and checks for completed fields")>
        <cfreturn this>
    </cffunction>
    
    <cffunction name="validate" access="public" output="false" returntype="struct">
        <cfargument name="fields" type="string" required="true" />
        <cfargument name="collection" type="struct" required="true" />
        
        <cfset var _result = structNew() />
        <cfset var _required = arguments.fields />
        <cfset var _message = '' />
        
        <cfset _result.message = _message />        
        <cfset _result.success = true />

        <cfloop list="#_required#" index="i" delimiters=",">
            <cfif structKeyExists(collection,i) and collection[i] eq ''>
                <cfset _message = listAppend(_message,i,',') />
            </cfif>
        </cfloop>
        
        <cfif _message neq ''>
            <cfset _result.success = false />
            <cfset _result.message = 'Please complete the following fields :>br/<'&rereplacenocase(_message,',',', ','ALL') />
        <cfelse>
            <cfset _result.message = 'Your details have been sent' /> 
        </cfif>

        <cfreturn _result />    
    </cffunction>


</cfcomponent>

 

The component is called by using the following syntax from with a Coldbox handler. The required fields need to be passed into the custom plugin, as we as the complete event. From here the RequiredFields plugin will ensure that the required fields are not blank.

<cfset var _required = 'name,email,comments' />
<cfset var _result = getMyPlugin('requiredFields').validate(_required,event.getCollection()) />

1 response to “Coldbox - Required Form Fields Plugin”

  1. Lana Leech Says:
    Hey, I think your website might be having browser compatibility issues. When I look at your blog in Ie, it looks fine but when opening in Internet Explorer, it has some overlapping. I just wanted to give you a quick heads up! Other then that, awesome blog!
leave a reply

Leave this field empty: