Search code examples
jsfhyperlinkrequired

How to validate click of h:outputLink with imagined required="true"?


I'm trying to put validation in my Link. when the user click on commandButton without click on outputLink user gets an error message. I'm using required="true" but it doesn't work.

<h:form>
    <h:outputLink value="https://www.google.com/" required="true">test</h:outputLink>
    <h:commandButton value="Submit"    action="#{userTest.test()}"/>
</h:form>

Solution

  • Associate a required hidden input with the link and set its value via JS.

    Here's a kickoff example which assumes the hidden input is 1st sibling of the link.

    <h:form>
        <h:outputLink 
            value="http://google.com" 
            target="_blank"
            onclick="this.nextSibling.value=true">test</h:outputLink>
        <h:inputHidden 
            required="true" 
            requiredMessage="You need to click that link!" />
        <h:commandButton value="submit" />
        <h:messages />
    </h:form>