Search code examples
jsfbean-validationdisabled-input

Bean validation and complex objects


I have a bean with several fields

@NotNull( message = "{ch.ethz.id.wai.doi.validation.doi.missingdoi}" )
@Pattern( regexp = "10\\.[\\d.]+/.*", message = "{ch.ethz.id.wai.doi.validation.doi.invalidDoi}" )
private String  doi;

@ManyToOne
@NotNull( message = "{ch.ethz.id.wai.doi.validation.doi.missingpool}" )
private DoiPool doiPool;

The first annotations work as expected with the following in JSF

<h:inputText
    id       = "doi"
    value    = "#{detailModel.afterObject.doi}"
/>
<h:messages for="doi" style="clear: both; color: red;"/>

For the other field I have a disabled input text where I put the name of the referenced object . The user is able to specify an object by clicking a button and choosing it in a separate view.

<h:inputText
    id       = "doiPool"
    value    = "#{detailModel.afterObject.doiPool.name}"
    disabled = "true"
/>
<h:messages for="doiPool" style="clear: both; color: red;"/>

As the inputText does not refer to detailModel.afterObject.doiPool but to its name nothing happens.

How can I force the validation on detailModel.afterObject.doiPool even if it not directly editable with an input field?


Solution

  • As an addition to the answer of BalusC:

    The @NotNull is specified on a DoiPool object and not his name (that was shown in the text field). To make it work the text field needs to be bound to the validated field:

    <h:inputText
      id       = "doiPool"
      value    = "#{detailModel.afterObject.doiPool}"
      disabled = "#{facesContext.renderResponse}"
    >
        <f:converter converterId="ch.ethz.id.wai.doi.DoiPoolConverter"></f:converter>
    </h:inputText>
    

    The converter simply returns the getName() of the object.

    @FacesConverter( "ch.ethz.id.wai.doi.DoiPoolConverter" )
    public class DoiPoolConverter implements Converter
    {
    
        /**
         * This converter works only in the other direction.
         *
         * @return null
         */
        @Override
        public Object getAsObject( FacesContext facesContext, UIComponent uiComponent, String string )
        {
                return null;
        }
    
        @Override
        public String getAsString( FacesContext facesContext, UIComponent uiComponent, Object object )
        {
                if ( object instanceof DoiPool )
                {
                        return ( (DoiPool)object ).getName();
                }
                return null;
        }
    }