<p:outputLabel for="piBirthDay" value="Example label" />
<p:datePicker id="piBirthDay"
validatorMessage="You are not allowed"
value="#{data.motorbikePlateRequest.bikeOwner.birthday}"
showTime="false" required="true">
<f:validator binding="#{greaterOrEqual18YearOldValidator}" />
</p:datePicker>
=============================
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Arrays;
import java.util.Date;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
@ManagedBean(name = "greaterOrEqual18YearOldValidator")
public class GreaterOrEqual18YearOldValidator implements Validator {
@Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
if (value == null) {
return;
}
if (!isGreaterOrEqual18YearOld((Date) value)) {
String message = "You are not allowed to make a request";
FacesMessage facesMessage = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Validation Error", message);
throw new ValidatorException(Arrays.asList(facesMessage));
}
}
private boolean isGreaterOrEqual18YearOld(Date value) {
final int YEAR_OLD = 18;
LocalDate idealDateTime = this.convertToLocalDateViaInstant(value).plusYears(YEAR_OLD);
return idealDateTime.compareTo(LocalDate.now()) < 0; // when the ideal date time less than now
}
private LocalDate convertToLocalDateViaInstant(Date dateToConvert) {
return dateToConvert.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
}
}