Search code examples
liferayliferay-auialloy-ui

How to make AUI validation apply only when a check box is selected?


I have fields in an aui form that I only want to be required when a corresponding checkbox is selected, otherwise they're not required. I'll enable these input fields using <aui:script> once the check box is enabled and only then aui validation should work.

I have tried with hiding the <aui:validator> depending condition in script.

How do I enable the validation only if my check box is selected in aui?

<aui:form action="" method="post">
<aui:input type="checkbox" name="employeeId" id="employeeId"></aui:input>

<div id="employeeDetails">
    <aui:input type="text" name="name" id="employeeId2">
        <%
            if (true) { //default i kept true how to check this condition on check box basic
        %>
        <aui:validator name="required"'  />
        <%
            }
        %>
    </aui:input>
    <aui:input type="text" name="email" id="employeeId3">
        <%
            if (true) {
        %>
        <aui:validator name="required" />
        <%
            }
        %>

    </aui:input>
</div>
<aui:button-row>
    <aui:button type="submit" />
</aui:button-row>
</aui:form>

<aui:script>
AUI().use('event', 'node', function(A) {
   A.one('#employeeDetails').hide(); // to hide div by default

   var buttonObject = A.all('input[type=checkbox]');
   buttonObject.on('click', function(event) {
     if (A.one("#<portlet:namespace/>employeeId").attr('checked')) { 
        A.one('#employeeDetails').show(); //for checked condition
     } else {
        A.one('#employeeDetails').hide(); // for non checked condition
     } 
   });
});
</aui:script>

Reference images:

Before enabling the check box

[Before enabling the check box]

Check box enabled:

[check box enabled]


Solution

  • This sample if(true) bothers me - it's evaluated server side on the JSP and won't have any effect, since true is always true.

    However, your question is well documented within Liferay's documentation: Look for "Conditionally Requiring A Field"

    Sometimes you’ll want to validate a field based on the value of another field. You can do this by checking for that condition in a JavaScript function within the required validator’s body.

    Below is an example configuration:

    <aui:input label="My Checkbox" name="myCheckbox" type="checkbox" />
    
    <aui:input label="My Text Input" name="myTextInput" type="text">
      <aui:validator name="required">
        function() {
          return AUI.$('#<portlet:namespace />myCheckbox').prop('checked');
        }
      </aui:validator>
    </aui:input>