Mateusz Gaweł
Mateusz Gaweł

Reputation: 683

JSF validator with custom method

This is fragment of my Bean:

public class WaiterBean extends Connector
{
    private String PIN;
    private String name = null;

    public void setPIN(String PIN)
    {
        this.PIN = PIN;
    }
    public String getPIN() 
    {
        return PIN;
    }
    public String getName() 
    {
        return name;
    }
    public String isPINCorrect(String PIN) 
    {
        try 
        {
            resultSet = statement.executeQuery(
                "SELECT name FROM dbo.waiters WHERE PIN=" + PIN);
            while(resultSet.next())
            {
                name = resultSet.getString("name"); 
            }
        } 
        catch (SQLException se) 
        {
            System.out.println(se.getMessage() + "**"
                + se.getSQLState() + "**" + se.getErrorCode());
        }
        if(name == null)
            return "invalid";
        else
            return "valid";
    }
}

This is validator bean:

public class PINValidator implements Validator
{

    @Override
    public void validate(FacesContext fc, UIComponent uic, Object o) throws ValidatorException 
    {
        String PIN = o.toString();
        if(PIN.length() < 4)
        {
            FacesMessage msg = new FacesMessage("PIN too short");
            msg.setSeverity(FacesMessage.SEVERITY_ERROR);
            throw new ValidatorException(msg);
        }
    }
}

And this is how I use it:

<h:form>
    <h:panelGrid columns="2">
        ENTER PIN
        <h:inputText id="PIN" maxlength="4" size="4" value="#{waiterBean.PIN}">
            <f:validator validatorId="com.jsf.PINValidator" />
        </h:inputText>
    </h:panelGrid>
    <h:message for="PIN"/> 
    <br />
    <h:commandButton value="SEND" action="#{waiterBean.isPINCorrect(waiterBean.PIN)}" />
    <br />
</h:form>

Everything works fine, but I think it's good practice to include the isPINCorrect method in the validator class (am I wrong?). I can implement the method in the validator, but then I have a problem how to setName for the WaiterBean and it's needed for the application.

How should I resolve the problem? Or another question, should I even try to resolve it?

Upvotes: 1

Views: 2528

Answers (1)

Ozan Tabak
Ozan Tabak

Reputation: 672

You can access a session scoped managed bean from a validator like this:

facesContext.getExternalContext().getSessionMap().get("waiterBean");

But I don't think this is the best practice in your case because a validator should not modify data, should only check for the validity of the input. The main reason for this at the validation phase the model is not updated yet, and modifying your bean in the validator can cause some side-effects.

Take a look at JSF Lifecycle

Upvotes: 2

Related Questions