tags:

views:

405

answers:

4

When facing the problem of validating a property in a JSF2 application there are two main approaches.

Defining the validation on the ManagedBean using an Annotation

@ManagedBean
public class MyBean {
    @Size(max=8)
    private String s;

    // Getters setters and other stuff.
}

or declaring it on the jsf page:

<h:inputText value="#{myBean.s}">
    <f:validateLength maximum="8"/>
</h:inputText>

It happens that I can't decide for none of them. The first one is nice because it removes some code from the jsf pages (which is always good since those pages are not eye friendly by definition) but makes harder to see 'at a glance' what's going on with the page when checking the jsf file.

Which one do you think is clearer? Nicer? Better?

+2  A: 

I would pump for validation on the ManagedBean, this removes logic from the JSF the VIEW in model view Controller. and should keep the JSF souly responsible for displaying the Model. Also having this on the managed bean ensures that where ever this is updated validation is applied. This is more DRY(Don't repeat yourself).

David Waters
+2  A: 

Those bean validation annotations can be used for more other purposes than only taking over the configuration in the view. Also, those annotations keeps the information there where it actually belongs. Also, often a model can be reused for other views, this way you don't need to repeat yourself there.

BalusC
+2  A: 

Richfaces allows you to use them together. See <rich:graphValidator> (and beanValidator as well).

These tags say: "apply JSF validation based on javax.validation (or Hibernate validator) rules".

Bozho
A: 

There is another advantage of the managedBean approach. If the information being displayed by the JSF is also available via a web service (WS) then the actual validation code can be factored out into a validation class and used for both the JSF and the WS ensuring that all information in the system is valid.

Martin