CQ5 DateTime field validation

I’ve been working on CQ5 recently and got stuck on defined user requirement to have only date/time combinations enter only be valid if they are NOT in the past. I couldn’t find a specific solution to this after doing some googling, but here is the solution I came up with in the end that works pretty well and is in line with existing validation routines and behaviour.

NOTE: I am using Adobe CQ5.6

Firstly in your dialog.xml add a validator entry for your datetime field.


<scheduled jcr:primaryType="cq:Widget"
           fieldLabel="Scheduled:"
           name="./scheduled"
           xtype="datetime"
           validator="function(value) { return Validation.isInPast(value); }"
           invalidText="Please provide a valid scheduled date and time." />

Now create a folder called clientlibs in your component folder (same location where your dialog.xml file is), which will have the property jcr:primaryType=”cq:ClientLibraryFolder” and have a categories element which is defined to your application specific category. See here for more information on what to set this to. In my case I want the dialog to be used as part of a workflow, therefore to I need to set it to categories=”[cq.workflow]”. In XML the .content.xml file would look like this:

<?xml version="1.0" encoding="UTF-8"?>
<jcr:root xmlns:sling="http://sling.apache.org/jcr/sling/1.0" xmlns:cq="http://www.day.com/jcr/cq/1.0" xmlns:jcr="http://www.jcp.org/jcr/1.0"
 jcr:primaryType="cq:ClientLibraryFolder"
 categories="[cq.workflow]" />

Now in your clientlibs folder create a Validation.js file and add the following code to it:

Validation = function() {
 return {
 isInPast : function(value) {
 var scheduledDate = value;
 var now = new Date();
 if (scheduledDate < now) {
 return "The selected date of " + value + " is before the current system date of " + now;
 } else {
 return true;
 }
 }
 };
}();

Also under your clientlibs folder create a file called js.txt and add the following content:

Validation.js

If required deploy your code and open your dialog. Depending on your validation configuration, when the user enters a date in the past the user will receive an error and the fields within the datetime component will be highlighted stating that the date/time combination they have entered is in the past.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.