Rico Ocepek
Rico Ocepek

Reputation: 815

How to validate a required field? Throw exception in setter?

Is it possible to throw a exception from a managed bean setter?

For example i would create a setter like:

public void setName(String _name) throws Exception{
    if(_name.compareTo("")==0)
        throw new Exception("Name is empty!");

    name=_name;
}

If I would now try to submit a form with an empty name-field it should display "Name is empty!".

I know I could handle this inside the action method of my form but the solution above seems to be better practise to me.

Upvotes: 0

Views: 928

Answers (1)

Daniel
Daniel

Reputation: 37061

You're supposed to use JSF builtin validation facilities. In your case you better use the required and requiredMessage attributes.

Something like this:

<h:inputText id="name" value="#{myBean.name}" required="true" 
    requiredMessage="Name is empty!"/>
<h:message for="name" />

Upvotes: 3

Related Questions