Custom validator for a SelectMany component

I did not succeed at validating a selectManyCheckBox with a custom validator.

I want to validate that the user selected at least 1 and at most 3 checkboxes.

The UIComponent.getSelectedValues always returns an array of length 0, even when some boxes are checked.

Page code:

<h:selectManyCheckbox id="selectProfessions" value="#{userBackingBean.selectedProfessionIDs}" layout="pageDirection" styleClass="category">

<f:selectItems value="#{categoryTreeBackingBean.professionSelectItems}" />

<f:validator validatorId="com.studio184.news.ui.validator.SelectCategoriesValidator"/>

</h:selectManyCheckbox>

Validate method:

UISelectMany select = (UISelectMany)component;

if (select.getSelectedValues() == null || select.getSelectedValues().length < 1 || select.getSelectedValues().length > 3) {

String summary = ...

String detail = ...

FacesMessage message = new FacesMessage(summary, detail);

message.setSeverity(FacesMessage.SEVERITY_ERROR);

throw new ValidatorException(message);

}

Any help would be greatly appreciated.

Bruno

http://www.practicalsoftwarearchitect.com

[1214 byte] By [brunocollet] at [2007-9-30 21:32:41]
# 1

In general, the value property is set at the end of the Process Validations phase.

You can use getSubmittedValue() to access the submitted values.

More simply, you can use the third argument of the validate method which is the same as the submitted value.

For example:

public void validate(FacesContext arg0, UIComponent arg1, Object arg2)

throws ValidatorException {

Object values[] = (Object [])arg2;

if (values() == null || values().length < 1 || values().length > 3) {

// throw exception!!

}

}

yuki.yoshida at 2007-7-7 3:04:16 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 2

Thanks it works fine now :)

I have just read the JSF processing phases and it greatly clarifies why it did'nt work before.

Just one little note: if no checkbox is selected, validation does not occur at all. For this reason, testing that values.length < 1 in the validate method is useless. But setting the selectManyCheckbox with required="true" does the trick.

Bruno

http://www.practicalsoftwarearchitect.com

brunocollet at 2007-7-7 3:04:16 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...