Simple Multifield Max Item Validation for AEM 6.4 | Perficient Digital

Simple Multifield Max Item Validation for AEM 6.4

I’ve recently had the need to validate that a multifield does not exceed a specific number of items, this post is a short code snippet that will show you how I did that.

 

This solution simple enough, it takes a few minutes to adapt it to a min validation or validating for a specific number of items.

 

Create a Clientlib

First, you’ll need to create a clientlib with categories cq.authoring.editor.hook or any other category that will make this code available to the Editor frame.

Add JS and CSS

here is my basic JS validator:

See Granite UI docs for the validation API

 

$(window).adaptTo("foundation-registry").register("foundation.validation.validator", {
  // check elements that has attribute data-foundation-validation with value starting with "multifield-max"
  selector: "[data-foundation-validation^='multifield-max']",
  validate: function(el) {
    // parse the max number from the attribute value, the value maybe something like "multifield-max-6"
    var validationName = el.getAttribute("data-validation")
    var max = validationName.replace("multifield-max-", "");
    max = parseInt(max);

    // el here is a coral-multifield element
    // see: https://helpx.adobe.com/experience-manager/6-4/sites/developing/using/reference-materials/coral-ui/coralui3/Coral.Multifield.html
    if (el.items.length > max){
        // items added are more than allowed, return error
        return "Max allowed items is "+ max
    }
  }
});

Now the CSS:

We are adding this to show the border when the multifield is invalid

coral-multifield[aria-invalid=true] {
    border: solid 1px #f00;
}

Now to use, just add validation="multifield-max-6" to a multifield, here is an example:

<socialMediaIcons
    jcr:primaryType="nt:unstructured"
    sling:resourceType="granite/ui/components/coral/foundation/form/multifield"
    class="full-width" fieldLabel="Social Media Icons"
    composite="{Boolean}true"
    validation="multifield-max-6">

Now, once you open your dialog and start adding fields, you’ll get an error when the items are more than the max value.

Here is an example where I set validation="multifield-max-1" so when I try to add more than one item I se an error:

Leave a Reply