April 26, 2020
Estimated Post Reading Time ~

AEM Tag field validation

AEM6 uses the Coral UI framework for touch UI rendering. So if you need to implement field validation, you should register a validator on that field supported by Coral UI.

To implement validation on the tag input field you can use the following sample code.

1. In your tagspicker input field add one property- tagsMessage (Set value to the validation message). Look at the screenshot below-



2. Create a clientLibs Folder with category- "cq.authoring.dialog" and add a JS file having the following code-

;(function($, $document) {
"use strict";
$document.on("dialog-ready", function() {
//Register Tag Field Validator
$.validator.register({
selector: "input.js-coral-pathbrowser-input",
validate: function(el) {
var field = el.parent().parent();
var message = field.attr("data-tagsMessage");
if (message) {
var taglist = field.parent().find("ul[data-init~=taglist] li");
var length = taglist.length;
if (length == 0) {
var message = field.attr("data-tagsMessage") + "";
return message;
}
}
}
});

// Register to listent custom event 'custom-tagpicker-tag-selected'
$("input.js-coral-pathbrowser-input").on('custom-tagpicker-tag-selected', function(event) {
var el = $(this);
el.checkValidity();
el.updateErrorUI();
});

});


//Below code triggers a custom event when a new tag is selected from tag browser so that field can be revalidated
$(document).on("foundation-contentloaded", function(event) {
var rel = ".js-cq-TagsPickerField",
rel2 = ".tagspicker";

var $target = $(event.target);
var $pathBrowser = $target.find(".js-cq-TagsPickerField.coral-PathBrowser");
$pathBrowser.each(function() {
var tagBrowser = $(this).data("pathBrowser");
var $input = tagBrowser.inputElement;
// Handle selections from the PathBrowser picker
tagBrowser.$picker.on("coral-pathbrowser-picker-confirm.tagspicker", function(e) {
$input.val("");
$input.trigger('custom-tagpicker-tag-selected');
});
//Handle keypress event
tagBrowser.inputElement.off("keypress" + rel2).on("keypress" + rel2, function(e) {
var $pathBrowser = $(this).closest(rel + ".coral-PathBrowser");
if (e.keyCode === 13) {
e.preventDefault();
$input.trigger('custom-tagpicker-tag-selected');
}
});

// Handle type-in from the PathBrowser textfield
tagBrowser.dropdownList.on("selected" + rel2, function(e) {
var $pathBrowser = $(this).closest(rel + ".coral-PathBrowser");
jQuery.get(e.selectedValue + ".tag.json", {},
function(data) {
if (data !== undefined) {
$input.trigger('custom-tagpicker-tag-selected');
}
},
"json");

});

});
});
//Register Tag Validator ENDS

})($, $(document));



Once you have added this JS to your page, you can call it in any number of fields. You just need to add the one property to the fields(as mentioned in Step 1 above) where you want tag validation.


By aem4beginner

No comments:

Post a Comment

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