I have a form with two input fields that have to be validated together. I used this BalusC tutorial as starting point.
The requirement is a logical XOR: one of the fields must be filled but not both together.
This works fine for all cases except this one:
1) Fill the first field and let the second blank
2) Move to the next page (values get saved)
3) Go back to the first page, delete first field and fill second field.
Then I get the error message from my validator ("Do not fill both fields") although I deleted the first.
Here is the code:
<h:inputText id="bbvol" size="10" value="#{a6.behandlungsvolumen.wert}"
required="#{empty param['Laborwerte:pvol']}">
<f:convertNumber locale="de"/>
</h:inputText>
<h:inputText id="pvol" size="10" value="#{a6.plasmavolumen.wert}"
required="#{empty param['Laborwerte:bbvol']}">
<f:convertNumber locale="de"/>
<f:validator validatorId="volumeValidator" for="pvol"/>
<f:attribute name="bbv_value" value="Laborwerte:bbvol" />
</h:inputText>
VolumeValidator:
public class VolumeValidator implements Validator {
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
// Obtain the client ID of the first volume field from f:attribute.
String bbvolID = (String) component.getAttributes().get("bbv_value");
// Find the actual JSF component for the client ID.
UIInput bbvolInput = (UIInput) context.getViewRoot().findComponent(bbvolID);
// Get its value, the entered value of the first field.
Number bbvol = (Number) bbvolInput.getValue();
// Get the value of the second field
Number pvol = (Number) value;
// Check if only one of the fields is set
if (bbvol != null && pvol != null) {
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Do not fill both fields!", null));
}
}
}
Debugging this case reveals that the line
Number bbvol = (Number) bbvolInput.getValue();
still holds the old value and not the new.
I tried to use getSubmittedValue()
instead of getValue()
and this works. But javadoc for this method says:
This method should only be used by the decode() and validate() method of this component, or its corresponding Renderer.
I am not sure if I can use this method without running in problems later.
So my questions are:
What is the reason for this issue?
Is using getSubmittedValue()
instead of getValue()
a real solution?