Search code examples
javascriptjsfjsf-2primefaces

Client validation in Primefaces


I need to validate (check whether the number is less than 50000) a field on html site, field in inside some form.

<p:inputText id="xid" styleClass="span3"value="#{user.xd}" maxlength="5" required="true">
    // the validator does not work
    <f:validateLongRange maximum="50000" minimum="1"/>
    <p:clientValidator event="keyup"/>
</p:inputText>

I need to verify it during user's writing data. I also was checking jQuery code:

$(document).ready(function() {
        $("#form").validate({
            rules: {
                xid: {
                    required: true,
                    maxlength: 5,
                    min: 1,
                    max: 50000
                }
            },
            messages: {
                xid: {
                    required: "This is mandatory. Either generated or  manually entered!",
                    maxlength: "Max length is 5 digits",
                    max: "Max Value is 50000",
                    min: "Min is 1",
                    pattern: "Cannot contain characters nor starting with 0."
                }
            }
        });
});

The issue in the solution is the fact, that when JSF is applied the id's of forms are no so simple like "form"- names contains also ":" and JavaScript cannot handle them.


Solution

  • Forget about adding extra jQuery code and just go with the JSF validator along with the PrimeFaces client validator tag. You'll see how the input field turns red for values greater than 50000. I personally tend to use the change event instead of keyUp, I consider it to be more user friendly:

    <html xmlns="http://www.w3.org/1999/xhtml"
        xmlns:h="http://xmlns.jcp.org/jsf/html"
        xmlns:f="http://xmlns.jcp.org/jsf/core"
        xmlns:p="http://primefaces.org/ui"
        xmlns:comp="http://java.sun.com/jsf/composite/comp"
        xmlns:ui="http://java.sun.com/jsf/facelets">
    <h:head />
    <h:body>
        <h:form>
            <p:messages autoUpdate="true" />
            <p:inputText value="#{val}" maxlength="5" required="true">
                <f:validateLongRange maximum="50000" minimum="1" />
                <p:clientValidator event="change" />
            </p:inputText>
            <p:commandButton value="Check" />
        </h:form>
    </h:body>
    </html>
    

    Don't forget to enable the client side validation in your web.xml:

    <context-param>
        <param-name>primefaces.CLIENT_SIDE_VALIDATION</param-name>
        <param-value>true</param-value>
    </context-param>
    

    See also: