Skip to content

Instantly share code, notes, and snippets.

@messaoudi-mounir
Created April 26, 2015 14:09
Show Gist options
  • Save messaoudi-mounir/6ee148f32ae064011e52 to your computer and use it in GitHub Desktop.
Save messaoudi-mounir/6ee148f32ae064011e52 to your computer and use it in GitHub Desktop.
Jsf - default global validator for all or specific componant (Primefaces example)
package commons.web.jsf.validator;
import java.util.Date;
import java.util.Map;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import org.primefaces.component.calendar.Calendar;
import org.primefaces.validate.ClientValidator;
import dz.gov.mesrs.sii.commons.web.util.CommonMessagesUtils;
@FacesValidator(CalendarDateRangeValidator.VALIDATOR_ID)
public class CalendarDateRangeValidator implements Validator, ClientValidator {
public static final String VALIDATOR_ID = "primefaceDateRangeValidator";
@Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
// you can personalize the validator for other componants
if (!(component instanceof Calendar))
return;
Date date = (Date) value;
if (date == null)
return;
Date mindate = (Date) component.getAttributes().get("mindate");
Date maxdate = (Date) component.getAttributes().get("maxdate");
if (mindate != null && maxdate != null) {
if (mindate.after(date) || maxdate.before(date)) {
throw new ValidatorException(CommonMessagesUtils.newBundledFacesMessage(FacesMessage.SEVERITY_ERROR,
"", "error_date_validator.date_range", ((Calendar) component).getLabel(), mindate, maxdate));
}
}
else if (mindate.after(date)) {
throw new ValidatorException(CommonMessagesUtils.newBundledFacesMessage(FacesMessage.SEVERITY_ERROR, "",
"error_date_validator.min_date", ((Calendar) component).getLabel(), mindate));
}
else if (maxdate != null) {
if (maxdate.before(date)) {
throw new ValidatorException(CommonMessagesUtils.newBundledFacesMessage(FacesMessage.SEVERITY_ERROR,
"", "error_date_validator.max_date", ((Calendar) component).getLabel(), maxdate));
}
}
}
@Override
public Map<String, Object> getMetadata() {
return null;
}
@Override
public String getValidatorId() {
return VALIDATOR_ID;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<faces-config version="2.1" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xi="http://www.w3.org/2001/XInclude" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_1.xsd">
<application>
<default-validators>
<validator-id>primefaceDateRangeValidator</validator-id>
</default-validators>
</application>
</faces-config>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment