March 30, 2020
Estimated Post Reading Time ~

Granite UI Jquery Validations in AEM 6.2

As a developer, I want AEM components to be author-friendly So that authors can fill the dialog with proper validations and check.
To achieve this in touch UI dialog, Jquery Validation plugins are the most preferable and widely used.

Use Case: I was having a dialog in which I was enabling two fields Contact Us Message and Time only when the author enters the mobile number.

If the author doesn’t enter anything in mobile no. field then both the fields will remain disabled.

How to achieve it:
1. Add a property validation in mobile,  contact us a message and time widget. This property will be used as a selector in jquery.
validation.PNG
Fig- Adding the validation property in the widget

2. Now with the help of the selector, the plugin is getting registered. Registering custom validators is done by calling the jQuery-based $.validator.register method.

$.validator.register({
   selector: "form [data-validation='cq-dialog-mobileNo']",
   clear: function(el) {
       var mobileMessage = $("form [data-validation='cq-dialog-mobileMessage']");
       var time = $("form [data-validation='cq-dialog-time']");
       if (el.val() != "") {
           mobileMessage.attr('disabled', false);
           time.attr('disabled', false);
       } else {
           mobileMessage.attr('disabled', true);
           time.attr('disabled', true);
       }
   }
});


Through this validator, when the author enters the mobile Number, it enables or disables the rest of the fields.

Now there is also a problem that when content loaded, it is not showing the appropriate behavior because the above validation only works when there are some changes to the mobile number field.


For Solving this issue, there is a need for calling clear() method when content is getting loaded.

/* call mobile tab validators on content loaded */
$(document).on("foundation-contentloaded", function(e) {

/* updateErrorUI is used to called clean method of validator */
   $("form [data-validation='cq-dialog-mobileNo']").updateErrorUI();
}

^E34DD7D6A308E21F2A71FB65C65958344AE58C0037F66A19C8^pimgpsh_fullsize_distr.png
Fig- Before entering the mobile number all field disabled

After entering the mobile number all field become enabled

enabled.PNG
Fig- After entering the mobile number all field become enable

In this example, one more tab E-Mail exists, in which email-id is disabled when an email message is given.

You can find code for the same also while downloading the package.
Demo Package Install


By aem4beginner

No comments:

Post a Comment

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