Using Manual Form Validation in JSF 2.0

Form validation means checking that all required form fields are present and in the proper format before or after submitting the form and display error messages showing what the problem was. There are several approaches of form validation in JSF. Here I will discus about the manual approach.

In manual approach we simply use string properties for bean and validate the form in setter methods or in action controller. We need to create custom error messages and store in FacesMessage and use h:messages to display list of error messages.

Bean File
ProductBean.java

package model;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;

@ManagedBean
public class ProductBean {

    private String pid, pname, price, qty;
    private double num_price;
    private int num_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 String getPrice() {
        return price;
    }
//Numeric Properties Conversion

    public void setPrice(String price) {
        this.price = price;
        try {
            num_price = Double.parseDouble(price);
        } catch (Exception e) {
        }
    }

    public String getQty() {
        return qty;
    }
//Numeric Properties Conversion

    public void setQty(String qty) {
        this.qty = qty;
        try {
            num_qty = Integer.parseInt(qty);
        } catch (Exception e) {
        }
    }

    public double getNum_price() {
        return num_price;
    }

    public int getNum_qty() {
        return num_qty;
    }

//Action Controller
    public String doPurchase() {
        FacesContext context = FacesContext.getCurrentInstance();
        if (getPid().equals("")) {
            context.addMessage(null,
                    new FacesMessage("Product id is required!"));
        }
        if (getPname().equals("")) {
            context.addMessage(null,
                    new FacesMessage("Product Name is required!"));
        }
        if (getNum_price() <= 0.10) {
            context.addMessage(null,
                    new FacesMessage("Purchase amount must be at least 0.10!"));
        }
        if (getNum_qty() <= 0) {
            context.addMessage(null,
                    new FacesMessage("Product quantity must greater than 0!"));
        }
        if (context.getMessageList().size() > 0) {
            return (null);//Return null to redisplay form
        } else {
            //apply business logic
            return ("show-purchase");//redirect to show-purchase.xhtml
        }
    }
}

productentry.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:messages styleClass="error"/>
                <h:panelGrid columns="2">
                    <h:outputLabel>Product ID:</h:outputLabel>
                    <h:inputText value="#{productBean.pid}"/>
                    <h:outputLabel>Product Name:</h:outputLabel>
                    <h:inputText value="#{productBean.pname}"/>
                    <h:outputLabel>Purchase Price:</h:outputLabel>
                    <h:inputText value="#{productBean.price}"/>
                    <h:outputLabel>Quantity:</h:outputLabel>
                    <h:inputText value="#{productBean.qty}"/>
                   
                </h:panelGrid>
                <h:commandButton value="Purchase"
                                 action="#{productBean.doPurchase}"/>
            </h:form>
        </f:view>
    </h:body>
</html>

show-purchase.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>Display Purchase</title>
    </h:head>
    <h:body>
        <f:view>
            <h:form>
                <h:outputLabel value="Purchase Info"/>
                <h:panelGrid columns="2">
                    <h:outputLabel>Product ID:</h:outputLabel>
                    <h:outputLabel value="#{productBean.pid}"/>
                    <h:outputLabel>Product Name:</h:outputLabel>
                    <h:outputLabel value="#{productBean.pname}"/>
                    <h:outputLabel>Purchase Price:</h:outputLabel>
                    <h:outputLabel value="#{productBean.price}"/>
                    <h:outputLabel>Quantity:</h:outputLabel>
                    <h:outputLabel value="#{productBean.qty}"/>                   
                </h:panelGrid>
            </h:form>
        </f:view>
    </h:body>
</html>

css/default.css

.error {
  color: red;
  font-weight: bold;
}

Screenshot:
jsf_manual_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

8,770` Total Views

One comment

  • your blogs are very helpful. It will better if you leave comment above the class.
    Can I contact you on mail ? I need help regarding JSF. I will be grateful to u .

Leave a Reply

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


+ 1 = four