May 9, 2020
Estimated Post Reading Time ~

Client-Side dialog validation in AEM

Here we will create a component that will have some basic fields. Let's say we will use two textfields and do validation on both of them.

Here the process follows,

1)Create dialog for the component as following,
<?xml version="1.0" encoding="UTF-8"?>
<jcr:root xmlns:cq="http://www.day.com/jcr/cq/1.0" xmlns:jcr="http://www.jcp.org/jcr/1.0"
    jcr:primaryType="cq:Dialog"
    xtype="dialog">
    <items jcr:primaryType="cq:TabPanel">
        <items jcr:primaryType="cq:WidgetCollection">
            <validationtab
                jcr:primaryType="cq:Panel"
                title="Validation Example Tab">
                <items jcr:primaryType="cq:WidgetCollection">
                    <exampletext0
                            jcr:primaryType="cq:Widget"
                            fieldLabel="First TextField"
                            fieldDescription="First field Description"
                            name="./text0"
                            xtype="textfield"/>
                    <exampletext1
                            jcr:primaryType="cq:Widget"
                            fieldLabel="Second TextField"
                            fieldDescription="Second field Description"
                            name="./text1"
                            xtype="textfield"/>
                </items>
            </validationtab>
        </items>
    </items>
    <listeners
        jcr:primaryType="nt:unstructured"
        beforesubmit="function(dialog) {return Example.checkFields(dialog);};"/>
</jcr:root>

2) After creating the dialog we will create a js file to get the values from 
the dialog and make it vaid.
This js file we make include in our clientLibrary folder ,
by including such, we make it call on load.
Here we are getting the two textfield values which are in the dialog.

Example = function() {
        return {
        
        // Dialog field cross validation.
        checkFields : function(dialog,maxWidth,maxHeight) {
            
            var textfieldArray = dialog.findByType("textfield");
            var textfieldLength0 = textfieldArray[0].getValue().length;
            var textfieldLength1 = textfieldArray[1].getValue().length;
            
            if((textfieldLength0 > 0 && textfieldLength1 > 0) || 
               (textfieldLength0 == 0 && textfieldLength1 == 0)) {
                // Both fields have or do not have a value
                return true;
            } else {
                // Cross validation fails
                CQ.Notification.notify(CQ.I18n.getMessage("Validation Error"),
                CQ.I18n.getMessage("Both fields must be filled or left empty."));
                return false;  
            }
        }
    };
    
}();


By aem4beginner

No comments:

Post a Comment

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