Touch UI allows developers to construct more powerful and dynamic functionality in order to enhance the authoring experience. Although Touch UI represents a big step forward, some useful features are missing. Some of these features are: Touch UI multifield support described in one of the previous posts, make select field to be required (will be described here), show/hide some part of a component dialog based on checkbox selection (will be described in some future blog post).
Since AEM 6.2 a new validation framework has been introduced. In order to make select field to be required, the validation code should be like this:
(function(window, $) { var SELECT_REQUIRED_VALIDATOR = "select.required", foundationReg = $(window).adaptTo("foundation-registry"); foundationReg.register("foundation.validation.validator", { selector: "select[data-validation='" + SELECT_REQUIRED_VALIDATOR + "']", validate: function(el) { var value = el.value; if (!value || value === '') { return "Please fill out this field." } } }); })(window, jQuery);
The most important things are on the selected lines. In line 2, select.required is the validator name and it’s used in a dialog definition, and in line 6 jQuery selector is used by the validation framework to select the right field on a Touch UI dialog. The rest is the implementation of a validation logic (lines 8-10). Parameter passed to the validation logic represents the selected component (DOM Element instance) which value is going to be validated.
By looking at the example above, you might notice that you can reuse it for different validations as well (eg. regex validation on a textfield). Proper validator name, field selector and a validation logic has to be implemented for the case you have.
The validator implemented above is used on the following way:
<selectField jcr:primaryType="nt:unstructured" sling:resourceType="granite/ui/components/foundation/form/select" fieldLabel="Some Select Field" validation="select.required"> <items jcr:primaryType="nt:unstructured"> <default jcr:primaryType="nt:unstructured" text="Please choose" value=""/> <option1 jcr:primaryType="nt:unstructured" text="Option 1" value="option1"/> <option2 jcr:primaryType="nt:unstructured" text="Option 2" value="option2"/> </items> </selectField>
In order to run the validation, the following has to be done:
- create a new client library folder (eg. /etc/clientlibs/myproject/author.dialog)
- set the value for categories property to be cq.authoring.dialog, and for dependencies to _ (underscore)
- place the validation code in some JS file, eg. /etc/clientlibs/myproject/author.dialog/js/required-select.js
- create js.txt file with the following content:
#base=js required-select.js