I am using JSF 2.0.
I have a h:selectOneMenu on my page which contains a list of values and there is one h:inputText on the same page, whose required should depend on the currently selected value of the h:selectOneMenu. Only a certain set of values should trigger the required check, others not.
This is what I have tried:
<h:inputText ... required="#{(selectedPaymentType.value == 'some value') || (selectedPaymentType.value == 'other value')}" />
In the code above #{selectedPaymentType} is definied in h:selectOneMenu binding.
There are 3 more values like this which should trigger the required attribute to true. This looks kind of clumsy. Are there better ways to do so?
Fant has given a hint in the right direction, that you should be using an enum which has a
requiredproperty, but it seems that you’re not entirely sure how to properly implement it. Admittedly, Fant’s answer is not elaborate enough. So here’s a more elaborate answer.Basically, you need to replace all dropdown values by an enum which look like this:
And use it as follows
with
(or if you’re using OmniFaces, use
<o:importConstants>, then you don’t need such a getter for the<f:selectItems>; no, you don’t need a converter in any case, JSF/EL has already builtin conversion for enums)See, the
requiredattribute is now so much more simplified as it’s already definied in the model associated with the selected value.