April 7, 2020
Estimated Post Reading Time ~

AEM Touch UI Dialog Validation

We know that Touch UI is based on Granite UI and JQuery, Now let us see how to use JQuery to validate a field in a dialog of a Touch UI.

Click here to check how the validation is done in Classic UI dialog.

Use Case: Validate a text field for a valid email address input.

Solution:
Step 1: Create a component under /apps/<project>
Step 2: Create cq:dialog for touch UI dialog and all the items required.

For Example, I have added a textfield by the name ’email’ for the OOB ‘text’ component

textfield

Step 3: Create clientlibs under the component folder. Add ‘cq.authoring.dialog‘ as categories. This enables us to use all the functions available in Granite UI.

Step 4: Add a script that has the validation logic using JQuery (ex: validation.js). Make sure you add that js in the js.txt file

Clientlibs

validation.js – Validation Script to check the valid email using the pattern



(function(document, $, ns) {
 "use strict";

 $(document).on("click", ".cq-dialog-submit", function(e) {
  e.stopPropagation();
  e.preventDefault();

  var $form = $(this).closest("form.foundation-form"),
   emailid = $form.find("[name='./email']").val(),
   message, clazz = "coral-Button ",
   patterns = {
    emailadd: /^([a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+(\.[a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)*|"((([ \t]*\r\n)?[ \t]+)?([\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*(([ \t]*\r\n)?[ \t]+)?")@(([a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.)+([a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.?$/i
   };

  if ((emailid != "" && !patterns.emailadd.test(emailid)) && emailid != null) {
   ns.ui.helpers.prompt({
    title: Granite.I18n.get("Invalid Input"),
    message: "Please Enter a valid Email Address",
    actions: [{
     id: "CANCEL",
     text: "CANCEL",
     className: "coral-Button"
    }],
    callback: function(actionId) {
     if (actionId === "CANCEL") {}
    }
   });

  } else {
   $form.submit();
  }
 });
})(document, Granite.$, Granite.author);

make sure you give ‘name’ of the field for which validation needs to be evaluated.

$form.find(“[name=’./email‘]”).val()

Now, this can be tested and it works as below




TouchUI dialog validation


By aem4beginner

No comments:

Post a Comment

If you have any doubts or questions, please let us know.