Skip to content

Instantly share code, notes, and snippets.

@Baztoune
Created February 20, 2013 11:54
Show Gist options
  • Save Baztoune/4995002 to your computer and use it in GitHub Desktop.
Save Baztoune/4995002 to your computer and use it in GitHub Desktop.
SimpleDateFormat (used by the default Converter, extended by Seam Converter) accepts a 2 digits year, even if the patter is set to a 4 digits year, so entering 27/10/45 was translated to 27/10/0045 by the Converter. My simple fix was to ensure the Date was between 1800 and 2100 (I could also throw an Exception if a regexp pattern was not matched…
package com.domiserve.servidom.util;
import java.util.Calendar;
import java.util.Date;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.ConverterException;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.faces.Converter;
import org.jboss.seam.annotations.intercept.BypassInterceptors;
import org.jboss.seam.ui.converter.DateTimeConverter;
@Converter(forClass = Date.class)
@Name(value = "org.jboss.seam.faces.dateConverter")
@BypassInterceptors
public class CustomDateConverter extends DateTimeConverter {
private static String DATE_PATTERN = "dd/MM/yyyy";
public CustomDateConverter() {
setPattern(DATE_PATTERN);
}
@Override
public Object getAsObject(FacesContext context, UIComponent component,
String value) {
Date d = (Date) super.getAsObject(context, component, value);
Calendar c = Calendar.getInstance();
c.clear();
c.set(Calendar.YEAR, 1800);
Date dateMin = c.getTime();
c.set(Calendar.YEAR, 2100);
Date dateMax = c.getTime();
if (d != null && (d.before(dateMin) || d.after(dateMax))) {
// interdit de saisir des dates avant 1800 et après 2100
FacesMessage message = new FacesMessage();
message.setSummary("Année invalide (format AAAA, entre 1800 et 2100)");
message.setSeverity(FacesMessage.SEVERITY_ERROR);
throw new ConverterException(message);
}
return d;
}
@Override
public String getAsString(FacesContext context, UIComponent component,
Object value) {
return super.getAsString(context, component, value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment