Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 935
Tomasz Waszczyk Avatar asked Mar 14 '26 15:03

Tomasz Waszczyk


1 Answers

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:

  • Primefaces clientValidator message not displayed
like image 169
Xtreme Biker Avatar answered Mar 16 '26 03:03

Xtreme Biker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!