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.
There are a couple of problems that I see here:
execute="@Form"
The above is incorrect.  If you wish to execute the whole form the correct value here is @form.
Once correcting this the txtStartDate component should update its binding value and can be set as the attribute for txtEndDate.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With