How can I validate an input text box based on a selection from the drop-down list?
2
votes
1 Answers
6
votes
You could pass the selected value of the dropdown as an attribute of the input component so that the validator can grab it.
E.g.
<h:selectOneMenu binding="#{menu}" value="#{bean.item}">
<f:selectItems value="#{bean.items}" />
</h:selectOneMenu>
<h:inputText value="#{bean.input}">
<f:attribute name="item" value="#{menu.value}" />
<f:validator validatorId="inputValidator" />
</h:inputText>
with
@FacesValidator("inputValidator")
public class InputValidator implements Validator {
@Override
public void validate(FacesContext context, UIComponent component, Object value) {
Object item = component.getAttributes().get("item");
// ...
}
}
Note that the ordering of the components matters. JSF processes UIInput
components in the order they appear in the view. If the dropdown component is placed after the input text component, then you need to pass #{menu.submittedValue}
as attribute, but at that point the value is not converted yet. You could if necessary workaround with a <h:inputHidden>
which is placed after the both components and put the validator in there.