PrimeFaces calendar accepts invalid dates as input

后端 未结 2 1324
再見小時候
再見小時候 2020-12-09 12:55

The problem I am having is with the PrimesFaces 3.4.1 calendar. When using the popup date picker activated either through the button or on input field focus you can only sel

相关标签:
2条回答
  • 2020-12-09 13:40

    In faces-config.xml add this

    <converter>
        <converter-id>localDateConverter</converter-id>
        <converter-class>com.utility.LocalDateConverter</converter-class>
    </converter>
    

    In the above class i.e LocaldateConverter add this below code

    /**
     * @param facesContext .
     * @param uiComponent .
     * @param input .
     * @return Object .
     */
    @Override
    public Object getAsObject(final FacesContext facesContext, final UIComponent   uiComponent, final String input) {
        if (StringUtils.isBlank(input)) {
            return null;
        }
        final String componentPattern = (String) uiComponent.getAttributes().get("datePattern");
        final String patternToUse = componentPattern != null ? componentPattern : CommonConstants.OUTPUT_DATE_FORMAT;
        try {
            final DateFormat fmt = new SimpleDateFormat(patternToUse);
            Date convertedDate = new java.sql.Date(fmt.parse(input).getTime());
            return convertedDate;
        } catch (Exception e) {
            throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Invalid Date Format", null));
        }
    }
    
    /**
     * @param facesContext .
     * @param uiComponent .
     * @param obj .
     * @return String .
     */
    @Override
    public String getAsString(final FacesContext facesContext, final UIComponent uiComponent, final Object obj) {
        if (obj==null) {
            return null;
        }
        final Date date = (Date) obj;
        return date.toString();
    }
    
    0 讨论(0)
  • 2020-12-09 13:49

    The <p:calendar> uses under the covers SimpleDateFormat which in turn uses by default lenient parsing, causing the overflowed values to roll over into the next date metric level. E.g. 32 January would become 1 February, etc.

    In plain Java terms, this can be turned off by DateFormat#setLenient(), passing false. See also among others this question: validating a date using dateformat.

    In JSF terms, you basically need to provide a custom converter which uses a non-lenient DateFormat. Fortunately, standard JSF already provides such one out the box in flavor of <f:convertDateTime>, so you could just make use of it directly.

    <p:calendar ...>
        <f:convertDateTime pattern="dd/MM/yyyy" />
    </p:calendar>
    
    0 讨论(0)
提交回复
热议问题