How to check input date on multiple templates?

In my jsf application, I know how to check user input for one pattern in mine ice:selectInputDateusing jsf converter:

   <f:convertDateTime pattern="MM/dd/yyyy"  />

but how to do this if I want the user to be able to enter a date in the format: "MM-dd-yyyy" too?

I think this can be done by adding a DateConverter from jsf, but I already tried with this, and I fail. Do you have an example to check the input date for multiple templates?

Thank.

UPDATE : I am using jsf 1.2

+3
source share
1 answer

Create your own converter that accepts multiple templates <f:attribute>on the component.

Here's what you would like to look like:

<h:inputText id="input" value="#{bean.date}">
    <f:converter converterId="multiDateConverter" />
    <f:attribute name="pattern1" value="MM/dd/yyyy" />
    <f:attribute name="pattern2" value="MM-dd-yyyy" />
</h:inputText>

( JSF 1.x,

<converter-id>multiDateConverter</converter-id>

faces-config.xml)

@FacesConverter(value="multiDateConverter")
public class MultiDateConverter implements Converter {

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) throws ConverterException {
        List<String> patterns = getPatterns(component);
        Date date = null;

        for (String pattern : patterns) {
            SimpleDateFormat sdf = new SimpleDateFormat(pattern);
            sdf.setLenient(false); // Don't parse dates like 33-33-3333.

            try {
                date = sdf.parse(value);
                break;
            } catch (ParseException ignore) {
                //
            }
        }

        if (date == null) {
            throw new ConverterException(new FacesMessage("Invalid date format, must match either of " + patterns));
        }

        return date;
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) throws ConverterException {
        return new SimpleDateFormat(getPatterns(component).get(0)).format((Date) value);
    }

    private static List<String> getPatterns(UIComponent component) {
        List<String> patterns = new ArrayList<String>();

        for (int i = 1; i < Integer.MAX_VALUE; i++) {
            String pattern = (String) component.getAttributes().get("pattern" + i);

            if (pattern != null) {
                patterns.add(pattern);
            } else {
                break;
            }
        }

        if (patterns.isEmpty()) {
            throw new IllegalArgumentException("Please provide <f:attribute name=\"patternX\"> where X is the order number");
        }

        return patterns;
    }

}

, ( ) . , , 05-10-2011, 05/10/2011.


, MM-dd-yyyy . dd-MM-yyyy?

+5

All Articles