Saturday 14 April 2018

Touch UI Validation in AEM - using Foundation Validation (Part 1)

In this post, you'll know how you can validate the fields in the touch ui dialog of AEM.
Now that  jQuery based validator, i.e. $.validator.register() is deprecated, we'll be using foundation-validation.

To select the node/field in the dialog for validation, just add any validation attribute along with your value in the properties of that node. Then in the component field markup you'll be able to see that data-attribute added.

For ex. I have added the below validation attribute to my summary textfield-



and the field markup of the dialog now looks like:


Now, this data-attribute will act as the selector for validating that particular field.

Use the below JS code snippet which you can put in clientlibs and add the categories as cq.authoring.dialog
(function ($window) {

 $window.adaptTo("foundation-registry").register("foundation.validation.validator", {
  selector: "[data-myapp-maxlength]",
  validate: function(el) {
    var maxlength = parseInt(el.getAttribute("data-myapp-maxlength"), 20);

    if (isNaN(maxlength)) {return;}

    var length = el.value.length;
    if (length > maxlength) {
      return "The field needs to be maximum " + maxlength + " characters. 
              It currently has a length of " + length + ".";
    }
  }, 
 });

})($(window));
The dialog validation looks like this:


Here, based on the validation attribute added (data-myapp-maxlength=20) and the logic written in js, it will validate the field length and show the error if validation fails.

You can also add show() and clear() method for this foundation-validation by referring the below interface:
interface FoundationValidationValidator {
  /**
   * Only the element satisfying the selector will be validated.
   */
  selector: string;
  /**
   * The actual validation function. It must return a string of error message
   * if the element fails.
   */
  validate: (element: Element) => string;
  /**
   * The function to show the error.
   */
  show: (element: Element, message: string, ctx: FoundationValidationValidatorContext) => void;
  /**
   * The function to clear the error.
   */
  clear: (element: Element, ctx: FoundationValidationValidatorContext) => void;
}
Referencehttps://helpx.adobe.com/experience-manager/6-3/sites/developing/using/reference-materials/granite-ui/api/jcr_root/libs/granite/ui/components/coral/foundation/clientlibs/foundation/js/validation/index.html

3 comments:

  1. I tried this error msg not populating but validation is working .
    Is there anything else that i need to add to make this working .

    ReplyDelete
  2. what if i have multiple components having same selector and i want to validate all of them with the same logic written in single js file what to do in that case????

    ReplyDelete