Search code examples
validationxpagesserverside-javascript

xPages using conditional custom validation


I don't know if this has been discussed in the past posts but I could not find anything similar so here goes my question: I have 14 fields on a custom control. Now on a particular condition during the workflow I need to ensure that the first 6 fields should be required (which can be done by using the required validator) and out of the other 8 fields the user should be forced to enter at least 2 fields. How can I achieve this? I am using server side validation for all fields with the property "disableClientSideValidation" set to true. I am not sure if a custom validator can be used in this context and if YES then how?


Solution

  • In your case, you'd use the validateExpression. The SSJS code there has to return true or false. Within the code you can access other fields with getComponent("otherFieldName").getSubmittedValue() and test this way how many fields are filled. In case of 0 or 1 return false and otherwise true.

    The validateExpression gets executed only if field is not empty. So, add the validationExpression to one of your first 6 required fields and add there the validateRequired too.

    Example:

     <xp:inputText
        id="inputRequired1"
        value="#{...}"
        disableClientSideValidation="true">
        <xp:this.validators>
            <xp:validateRequired message="field is required"></xp:validateRequired>
            <xp:validateExpression message="please, fill at least two fields">
                <xp:this.expression><![CDATA[#{javascript:
                num = 0;
                for (i = 1; i <= 8; i++) {
                    if (getComponent("inputText" + i).getSubmittedValue() !== "") {
                        num++;
                    }
                }
                if (num < 2) {
                    return false;
                }
                return true}]]></xp:this.expression>
            </xp:validateExpression>
        </xp:this.validators>
     </xp:inputText>
     <xp:inputText
        id="inputText1"
        value="#{...}">
     </xp:inputText>
     <xp:inputText
        id="inputText2"
        value="#{...}">
     </xp:inputText>
     ...