AJAX onSubmit validation in JSF 2.0

I started learning JSF2.0 and ran into a problem. Any advice on how to proceed would be appreciated.

I just renamed the form elements and classes for simplicity.

I have a form, for example:

<h:form id="frmSearch">
    <h:inputText id="dataPoint1" value="#{bean.dataPoint1}"/>
    <div id="dataPoint1Error" class="msgError">Value not found in database.</div>

    <h:inputText id="dataPoint2" value="#{bean.dataPoint2}"/>
    <div id="dataPoint2Error" class="msgError">Value not found in database.</div>

    <h:commandButton action="#{bean.validate}" type="submit" value="Search"/>


The "msgError" CSS class keeps the hidden element by default.

I would like to have basically a method in the bean class that validates the input by checking the database, and then if the value is not found, display an error message, or if found, then execute another method that does the actual functionality.

In my head, this will work like in Java (forgive any syntax errors by just typing as I think):

public class Bean {
    private String dataPoint1 = "";
    private String dataPoint2 = "";

    public boolean validate() {
        if(dao.fieldExists(this.dataPoint1) && dao.fieldExists(this.dataPoint2)) { //check the database
            return true;
        else {
            return false; //and show error div on screen

    public void performFunctionality() {
        //do whatever

    //getters and setters


Any advice would be greatly appreciated! Thank!


source to share

1 answer

You are not using the built-in JSF validator. Use it.

This is how it might look:

<h:form id="frmSearch">
    <h:inputText id="dataPoint1" value="#{bean.dataPoint1}" validator="#{bean.validateDataPoint}" />
    <h:message for="dataPoint1" />

    <h:inputText id="dataPoint2" value="#{bean.dataPoint2}" validator="#{bean.validateDataPoint}" />
    <h:message for="dataPoint2" />

    <h:commandButton action="#{bean.performFunctionality}" value="Search">
        <f:ajax execute="@form" render="@form" />



public void validateDataPoint(FacesContext context, UIComponent component, Object convertedValue) {
    if (!dao.fieldExists((String) convertedValue)) {
        throw new ValidatorException(new FacesMessage("Value not found in database."));


What performFunctionality()

should be done with the command line button action method.

When validation fails (i.e. ValidatorException

, the message will be displayed in the <h:message>

associated input component and the action method will not be invoked. The attribute validator

can also point to a fully fledged class that implements javax.faces.validator.Validator

. <f:ajax>

Added to make it ajax submit.

See also:

Wherever you learn JSF, make sure you also read the chapters on transformation and validation. Don't think too much about PHP / ASP / JSP / jQuery. JSF is a fully functional component based MVC framework.



All Articles