SpinOneSolutions | I waste my time so that you don’t have to…

Jan/09

13

CommonSpot Custom Field Validation

The Problem

You’re making a form and the out-of-the-box field types just aren’t cutting it.  Most web developers are familiar with this scenario.  The biggest culprits are phone numbers, addresses, and credit cards.

Let’s look at how you can quickly inject you’re own JavaScript validation into a CommonSpot form to handle any kind of validation that you want.

The Solution

We’ll make use of custom field types in order to accomplish our goal. First, we’ll make a custom render handler for our custom field type.  You may be thinking we should jump straight into the Site Admin, but that dialog is going to ask us to chose a custom render handler from a drop down list, so first we need to make the render handler so there’s something to choose from!

Fire up the FTP program of your choice, and navigate to the “customfields” folder in root.  I’ll be making a US Zip Code validator for this example so I’ll call my file “zip_render.cfm”.  If you want to register custom properties to your custom field type go ahead and create a “zip_props.cfm” in this folder now too.

Now that there’s something to choose; open Site Admin -> Field Masks & Custom Field Types -> Register New Field Type.  You should see something like this:

Add Custom Field Type Dialog

Type: The type of the field you’re creating.  It’s also what is displayed when choseing custom fields from the list.  I’ll call mine “Zip”.

Description: A human friendly description.  I’ll use “A valid US Zip code” for now. It can be a good idea to put what will and won’t match in here if you have the energy.

Property Module: Choose “zip_props.cfm” (whatever you called your file) if you made a Property Module or choose from the list of Standard Property Modules.  “Text” will work fine for me.

Render Module: Choose “zip_render.cfm” (whatever you called your file) from the list of Custom Render Modules.

Hit OK!

Now when you go to create/edit your form you’ll have a new field type available:

Edit Form Field - New custom field selected

Now all we have to do is add the custom validation. Here’s my custom render handler (zip_render.cfm):

<cfscript>
	// the fields current value
	currentValue = attributes.currentValues[fqFieldName];
	// the param structure which will hold all of the fields from the props dialog
	xparams = parameters[fieldQuery.inputID];

	request.youproject.utils.loadJQueryHeaders();
</cfscript>

<cfoutput>
	<script Language="JavaScript"  type="text/javascript">
		// javascript validation to make sure they have text to be converted
		#fqFieldName#=new Object();
		#fqFieldName#.id='#fqFieldName#';
		#fqFieldName#.tid=#rendertabindex#;
		#fqFieldName#.msg="Please enter a valid zip code.";
		#fqFieldName#.validator="#fqFieldName#_validater()";
		// push on to validation array
		<cfif xparams["REQ"]>
			vobjects_#attributes.formname#.push(#fqFieldName#);
			$(document).ready(function(){
				$("###fqFieldName#_label").wrap("");
			});
		</cfif>

		function #fqFieldName#_validater() {
			regex = new RegExp("(^\\d{5}$)|(^\d{5}-\\d{4}$)");
			return regex.test($("###fqFieldName#").val());
		}
	</script>
	<tr>
		<td nowrap="nowrap" align="left" width="25%" valign="baseline">
			<font face="Verdana,Arial" color="##000000" size="2">
                        <label for="#fqFieldName#">#xparams["LABEL"]#:</label>
                </font>
		</td>
		<td align="left" width="75%" valign="baseline">
			<input type="text" id="#fqFieldName#" name="#fqFieldName#" value="#currentValue#">
		</td>
	</tr>
</cfoutput>

Not too complicated but, let’s go over it real quick so you can expand and adapt this simple case to suit your needs.

“fqFieldName” is holding the CommonSpot generated name of your form field.  If you don’t include an input field for it, it won’t get saved when the user hits submit.

The JavaScript object of the same name (fqFieldName) is holding the specifics for our valdiation.  There’s the message to display on fail (msg) and the function to call on validation (validator).

I’ve wrapped the last bit in a conditional so that my custom validation is only added to the form’s validation array if I mark the field as required in the element.

The HTML for the display for the form field is left to you, the developer.

As always, Questions and Comments are welcome!

Share and Enjoy:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DZone
  • Kirtsy
  • Propeller
  • Reddit
  • Slashdot
  • StumbleUpon
  • Suggest to Techmeme via Twitter
  • Technorati

RSS Feed

6 Comments for CommonSpot Custom Field Validation

AtotoCafZoono | February 24, 2009 at 3:19 am

Thank you!

Василий | May 26, 2009 at 12:46 pm

Единственный минус – как-то все сухо…

KrisBelucci | June 2, 2009 at 8:41 pm

Hi, cool post. I have been wondering about this topic,so thanks for writing.

GarykPatton | June 15, 2009 at 6:47 pm

I think I will try to recommend this post to my friends and family, cuz it’s really helpful.

ialmerrissa | December 15, 2010 at 7:36 pm

Добрый день, перерыла весь интернет, очень много вакнсий, но реальных вакансий очень мало. Либо уже взяли человенка на работу, либо зарплата не очень. Кто какими сайтами пользуется, подскажите пожалуйста

foegreemose | December 29, 2010 at 6:42 pm

Радует, который ваш блог неумолчно развивается. Такие посты токмо прибавляют популярности.
http://lic1.ru – Недвижимость – статьи.

Leave a comment!

«

»

Find it!

Theme Design by devolux.org