JSF Form Validation using Custom Validator Methods

Using this approach we can write our own validator methods. Our custom method will throw a ValidatorException with a FacesMessage if validation fails and do nothing if validation succeeds.

We can’t use Validator Tags and custom method on same field.

Facelets code to use the custom validator:

<h:inputText id="someID" validator="#{someBean.someMethod}"/>

In this example I applied custom validator on Sales Price field.

Bean File
ProductBean2.java

package model;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.ValidatorException;

@ManagedBean
public class ProductBean2 {

    private String pid, pname;
    private double price, sprice;
    private int qty;

    public String getPid() {
        return pid;
    }

    public void setPid(String pid) {
        this.pid = pid;
    }

    public String getPname() {
        return pname;
    }

    public void setPname(String pname) {
        this.pname = pname;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public int getQty() {
        return qty;
    }

    public void setQty(int qty) {
        this.qty = qty;
    }

    public double getSprice() {
        return sprice;
    }

    public void setSprice(double sprice) {
        this.sprice = sprice;
    }

//Action Controller
    public String doPurchase() {

        //apply business logic
        return ("show-purchase");//redirect to return-purchase.xhtml

    }
//custom validation method
    public void validateSalePrice(FacesContext context,
            UIComponent componentToValidate,
            Object value)
            throws ValidatorException {
        if (sprice <= price) {
            FacesMessage message =
                    new FacesMessage("Sale Price must be higher than  "
                    + "Purchase Price");
            throw new ValidatorException(message);
        }
    }
}

productentry4.xhtml

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:h="http://java.sun.com/jsf/html">
    <h:head>
        <title>Product Entry</title>
        <link href="./css/default.css" 
              rel="stylesheet" type="text/css"/> 
    </h:head>
    <h:body>

        <f:view>
            <h:form>
                <h:panelGrid columns="3">
                    <h:outputLabel>Product ID:</h:outputLabel>
                    <h:inputText value="#{productBean2.pid}" required="true"
                                 requiredMessage="You must enter a Product ID"
                                 id="productID"/>
                    <h:message for="productID" styleClass="error"/>
                    <h:outputLabel>Product Name:</h:outputLabel>
                    <h:inputText value="#{productBean2.pname}" required="true"
                                 requiredMessage="You must enter a Product Name"
                                 id="productName"/>
                    <h:message for="productName" styleClass="error"/>
                    <h:outputLabel>Purchase Price:</h:outputLabel>
                    <h:inputText value="#{productBean2.price}" required="true"
                                 requiredMessage="You must enter an Purchase Price"
                                 converterMessage="Purchase Price must be a number"
                                 id="price"/>
                    <h:message for="price" styleClass="error"/>
                    <h:outputLabel>Sale Price:</h:outputLabel>
                    <h:inputText value="#{productBean2.sprice}" required="true"
                                 requiredMessage="You must enter an Sale Price"
                                 converterMessage="Sale Price must be a number"
                                 validator="#{productBean2.validateSalePrice}"
                                 id="sprice"/>
                    <h:message for="sprice" styleClass="error"/>
                    <h:outputLabel>Quantity:</h:outputLabel>
                    <h:inputText value="#{productBean2.qty}" required="true"
                                 requiredMessage="You must enter a Quantity"
                                 converterMessage="Quantity must be a whole number"
                                 id="qty"/>
                    <h:message for="qty" styleClass="error"/>

                </h:panelGrid>
                <h:commandButton value="Purchase"
                                 action="#{productBean2.doPurchase}"/>
            </h:form>
        </f:view>
    </h:body>
</html>

Screenshot:
jsf_custom_validator_form_validation

 

admin

Hello! I am Md. Abdul Bari; founder and admin of javaknowledge; currently providing training as a J2EE faculty in The Computers Ltd. Dhaka, Bangladesh under an IT Scholarship project provided by IDB-BISEW. I am a self learner and passionate about training and writing. I am always trying my best to share my knowledge through my blog.

More Posts - Website

Follow Me:
TwitterFacebookGoogle Plus

6,674` Total Views

3 comments

  • Sir, Sales price validation doesn’t work properly. and Here no show-parchase.jsp file found

    • Changes to be needed in ProductBean2.java. Declare a variable double pp. Add new method validatePurchasePrice and change the validateSalePrice as follows.

      double pp;
          //custom validation method
          public void validatePurchasePrice(FacesContext context,
                  UIComponent componentToValidate,
                  Object value)
                  throws ValidatorException {
              pp = ((Double) value).doubleValue();
          }
          //custom validation method
          public void validateSalePrice(FacesContext context,
                  UIComponent componentToValidate,
                  Object value)
                  throws ValidatorException {
              double sp = ((Double) value).doubleValue();
              System.out.println(sp +" "+pp );
              if (sp <= pp) {
                  FacesMessage message =
                          new FacesMessage("Sale Price must be higher than  "
                          + "Purchase Price");
                  throw new ValidatorException(message);
              }
          }
      

      Also make some changes in your productentry4.xhtml

      <h:inputText value="#{productBean2.price}" required="true"
                                       requiredMessage="You must enter an Purchase Price"
                                       converterMessage="Purchase Price must be a number"
                                       validator="#{productBean2.validatePurchasePrice}"
                                       id="price"/>
      

      See show-parchase.xhtml here. Just change the bean name.

Leave a Reply

Your email address will not be published. Required fields are marked *


× 1 = four