Yesterday I blogged about how to create a custom date renderer for CFGrid. Today I am going to add to that example how to validate the data entered into the CFGrid before it is sent to the cfc to update the database. The CFGrid (Ext.grid.EditorGrid) object has an event called "validateedit", which fires after a cell is edited, but before the value is set in the record. We will be adding a listener to that event that will validate the data that is being submitted and, if the data is not valid, display an alert message and cancel the changes.

You will see in the code below that I have a function called init which is called via ajaxOnLoad() after the grid is loaded. The init() function calls the setDateRenderer() (which will ensures the date is properly formatted when displayed in the grid), and it calls the addValidator() function I created to add a listener to the "validateedit" event. Now whenever the validateedit event fires, it will call the dataValidator() function. The dataValidator() function checks to see if the field that is being edited needs validation, and then validates the data if necessary. In this example, I added validation for the Expiration Date, and the numeric Sponsor ID for the coupon record. If the data fails validation an alert is thrown and the edit event is canceled(reverting the data back to it's original value).

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html>
<head>
   <title>CFGird Custom Date Validator</title>
   <!--- import the Ext date package --->
   <cfajaximport tags="cfinput-datefield">
   <!--- create javascript function for rendering dates --->
   <script language="JavaScript" type="text/javascript">
   setDateRenderer = function(){
      mygrid = ColdFusion.Grid.getGridObject('CouponsGrid');
      cm = mygrid.getColumnModel();
      cm.setRenderer(3, Ext.util.Format.dateRenderer('m/d/Y'));
      mygrid.reconfigure(mygrid.getDataSource(),cm);
   }
   dataValidator = function(editEvent){
      //Date Field Validation
      if (editEvent.field == "EXPIRATIONDATE"){
         if (isNaN(Date.parse(editEvent.value))){
            alert("Please enter a date in this field.");
            editEvent.cancel = true;
         }
         else {
            data = new Date(Date.parse(editEvent.value));
            editEvent.value = data.dateFormat("m/d/Y");
         }
      }
      //Numeric Field Validation
      if (editEvent.field == "SPONSORID"){
         if (isNaN(editEvent.value)){
            alert("Please enter a numeric value in this field.");
            editEvent.cancel = true;
         }
      }
   }
   addValidator = function(){
      mygrid = ColdFusion.Grid.getGridObject('CouponsGrid');
      mygrid.on('validateedit',dataValidator);
   }
   init = function(){
      setDateRenderer();
      addValidator();
   }
   </script>
</head>

<body>
<!--- Set up the Grid --->
<cfform id="CouponForm" name="CouponForm">
<cfgrid name="CouponsGrid"
format="html"
pagesize="10"
striperows="yes"
selectmode="edit"
bind="cfc:coupons.getCoupons({cfgridpage},{cfgridpagesize},{cfgridsortcolumn},{cfgridsortdirection})"
onchange="cfc:coupons.editCoupon({cfgridaction},{cfgridrow},{cfgridchanged})">

<cfgridcolumn name="Couponid" display="false" />
<cfgridcolumn name="SPONSORID" header="Sponsor" width="100"/>
<cfgridcolumn name="COUPON" header="Coupon" width="100"/>
<cfgridcolumn name="EXPIRATIONDATE" header="Exp Date" width="200"/>
</cfgrid>
</cfform>

<!--- use AjaxOnLoad to call the init() function --->
<cfset ajaxOnLoad("init")>
</body>
</html>

Click Here to See a Working Example

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
Samer Salameh's Gravatar Thank you for the effort.

I tried the example locally but it didn't work as required, also the working example is not working.
Can you help.

Thanks.
# Posted By Samer Salameh | 3/11/08 11:00 AM
Scott Bennett's Gravatar Sorry about that, It worked when I wrote the article but when I moved to my new hosting provider, I never updated the database connection info for this template. The working example should work properly now.
# Posted By Scott Bennett | 3/11/08 1:49 PM
JC's Gravatar I have tried the example given to validate data and receive the following Firebug error:
   
init is not defined
ColdFusion.Event.registerOnLoad(init,null,false,true);

I am new to CF8 and the EXT framework and am not sure what the issue is. Any help is greatly appreciated.
# Posted By JC | 1/13/09 12:52 PM
Scott Bennett's Gravatar @JC,

Make sure that the <script> block that contains your init() javascript function is in within the <head> and </head> tags. The ext stuff can be picky if you don't define all your javascript functions in the head of the html.

-Scott
# Posted By Scott Bennett | 1/13/09 12:59 PM
Sandy's Gravatar Is there a way using the cfgrig 8 with format="html" to be able to
have a ADD button that would add a record to the datagrid which is
is binded to a coldfusion component and then record would be
inserted in the database?
Is there a sample you know of for that?
# Posted By Sandy | 1/22/09 7:24 PM
Tones411's Gravatar Yes, make sure the javascript init() is in the head area.

Here's a trick to get it into the head area if you are using some kind of template system:

<cfsavecontent variable="javascript">
<script type="text/javascript">
function init(){
...
}
</script>
</cfsavecontent>
<cfhtmlhead text="#javascript#">

<cfset ajaxOnLoad("init")>
# Posted By Tones411 | 2/18/09 1:08 PM
khowell's Gravatar I have tried to incorporate this into an application that I am working with, but to no success. I keep getting a javascript error when the page loads. ('init' is undefined). In our environment, the head tag
is open and closed through an index page when the page loads, so I was using the cfhtmlhead tag to throw the init function into the <head> tags. Just can't seem to get it working, any thoughts?
# Posted By khowell | 4/20/09 6:42 PM
Bob Chesley's Gravatar I also ran into this and you can simply call the CF function directly in your page rather than using the ajaxonload function approach.

For example:
<script type="text/javascript">
ColdFusion.Event.registerOnLoad(init,null,false,true);
</script>
# Posted By Bob Chesley | 7/24/09 4:49 PM
S.C. Adams's Gravatar I am trying this in IE 7. And when it 'resets' the date it subtracts
one day. So 10/1/2009 becomes 11/30/2009. Works in
FF.
And I have no control over what browser my user uses.
# Posted By S.C. Adams | 12/9/09 11:39 AM
S.C. Adams's Gravatar I found a bug when working with the date validation part
It was not displaying the error message or returing the correct
original date.

I changed the code to this for the date validation.
if (isNaN(Date.parse(editEvent.value))){
alert("Please enter a date in this field.");
editEvent.cancel = true;
data = new Date(Date.parse(editEvent.originalValue));
}
else {
data = new Date(Date.parse(editEvent.value));
}
editEvent.value = data.dateFormat("m/d/Y");

ANd now it works like a charm.
# Posted By S.C. Adams | 12/16/09 6:30 PM
Jochen's Gravatar This example was exactly what I needed. But since CF 9 it is no longer running. No validation since the update of server. Any guess?
# Posted By Jochen | 4/13/10 10:11 AM
Scott Bennett's Gravatar @Jochen,

In ColdFusion 9 they changed to a new version of the underlying EXT framework. As a result most of the workarounds like this that I did in CF8 will not work. For this example I was making a custom date validator, because that was not built into CF8. However in CF9 they added some new options for the 'type' attribute in the 'cfgridcolumn' tag and now you can just use that to make sure the dates in a cfgrid are valid.

<cfform id="CouponForm" name="CouponForm">
<cfgrid name="CouponsGrid"
format="html"
pagesize="10"
striperows="yes"
selectmode="edit"
bind="cfc:coupons.getCoupons({cfgridpage},{cfgridpagesize},{cfgridsortcolumn},{cfgridsortdirection})"
onchange="cfc:coupons.editCoupon({cfgridaction},{cfgridrow},{cfgridchanged})">
<cfgridcolumn name="Couponid" display="false" />
<cfgridcolumn name="SPONSORID" header="Sponsor" width="100"/>
<cfgridcolumn name="COUPON" header="Coupon" width="100"/>
<cfgridcolumn name="EXPIRATIONDATE" header="Exp Date" type="date" width="200"/>
</cfgrid>
</cfform>

One thing to note however is that you in your cfc that is bound to the grid, you will need to add a function to convert the date string returned by the grid to a ColdFusion datetime value.

<cfscript>
function ISODateToTS(str) {
return ParseDateTime(ReplaceNoCase(left(str,16),"T"," ","ALL"));
}
</cfscript>

   <cfquery datasource="#THIS.dsn#">
   UPDATE COUPONS
   SET <cfswitch expression="#colname#">
    <cfcase value="EXPIRATIONDATE">#colname# = #createodbcdatetime(ISODateToTS(value))#</cfcase>
    <cfdefaultcase>#colname# = '#value#'</cfdefaultcase>
    </cfswitch>
   
   WHERE COUPONID = #ARGUMENTS.gridrow.COUPONID#
   </cfquery>
# Posted By Scott Bennett | 4/14/10 12:59 PM
Matt's Gravatar The dataValidator function part of this has been very helpful.
I'm using CF9 and I have a couple of cfgrids of html format in my app.

This code is useful for when a user has just changed the content of a cell.
But what about when they insert a new row (insert=yes) and the values are null?

If they submit the form, records w/null values will get submitted (I've checked, it works.)
I'd like to cancel the submit and reload the form page so it re-displays w/out the new insert rows (w/a little 'alert' as to why, of course).

But this is really throwing me for a loop
# Posted By Matt | 4/21/10 6:56 PM