Search code examples
formsvalidationjsfcommandbutton

Ignore custom validation, but not the required="true" depending on button pressed


I am using JSF and I want to validate a form. In the form is a text field that is validated by required="true" and a validator method.

<h:inputText
    required="true" requiredMessage="Please enter a topic" 
    validator="#{eventController.validateTopic}" />

To submit the form I have two buttons. When clicking on the first, it should be only validate if the field is empty. By the second one the custom validation should be additionally invoked. Is this possible?


Solution

  • First turn that validation method into a true Validator implementation.

    @FacesValidator("topicValidator")
    public TopicValidator implements Validator {}
    

    Then you can use it in a <f:validator> which supports disabled attribute.

    <h:inputText ...>
        <f:validator validatorId="topicValidator" disabled="..." />
    </h:inputText>
    

    To let it check if a certain button is pressed, just check the presence of its client ID in the request parameter map.

    <h:inputText ...>
        <f:validator validatorId="topicValidator" disabled="#{empty param[secondButton.clientId]}" />
    </h:inputText>
    ...
    <h:commandButton binding="#{secondButton}" ... />
    

    Note: do absolutely not bind it to a bean property! The above code is as-is. You should only guarantee that the EL variable #{secondButton} is unique in the current view and not shared by another component or even a managed bean.

    See also: