I want to validate two dates in a form before the user do the action. So I got a f:validator inside a p:calendar working with ajax, the problem is with the f:attribute. I am passing the start date as a parameter and the validator do not receive this date. However if press the action button, the date parameter is there in validation. I am using this post as a guide.
My xhtml is:
<p:column >
<p:calendar id="txtStartDate" binding="#{txtStartDate}"
pattern="dd/MM/yyyy"
value="#{myBean.bean.startDate}">
</p:calendar>
</p:column>
<p:column>
<p:calendar id="txtEndDate"
pattern="dd/MM/yyyy"
value="#{myBean.bean.endDate}">
<f:validator validatorId="validator.dateRangeValidator" />
<f:attribute name="fromDate" value="#{txtStartDate.value}" />
<p:ajax event="dateSelect" execute="@Form" update=":formHeader:messages" />
</p:calendar>
</p:column>
And Validator:
@Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
if (value == null || component.getAttributes().get("fromDate") == null) return;
Date endDate = (Date) value;
Date startDate = (Date) component.getAttributes().get("fromDate");
if (!endDate.after(startDate)) {
FacesMessage message = new FacesMessage("End date before the start date.");
message.setSeverity(FacesMessage.SEVERITY_ERROR);
addMessageOnSession(FacesMessage.SEVERITY_ERROR, "Invalid dates");
throw new ValidatorException(message);
}
}
Appreciate any help with that.
Anyway, a quick solution for me was add a listener=”” in ajax tag, so I am doing the validation at the bean. I dont know if this is the best way to do this, but solve my problem.