在JSF中格式化和验证日期

时间:2014-07-25 09:10:21

标签: java validation jsf date datetime

所以我想将dateinputfield格式化为“dd-MM-yyyy”,然后验证日期不是在明天之前。

这是我认为的相关代码:

   <h:inputText id="dueDate" required="true" value="#{submitRepairBean.dueDate}">
                <f:convertDateTime pattern="dd-MM-yyyy"/>   
                <f:validator validatorId="be.kdg.repaircafe.validators.DueDateValidator"/>
   </h:inputText>

这是我的自定义验证器:

@FacesValidator("be.kdg.repaircafe.validators.DueDateValidator")
public class DueDateValidator implements Validator {

    @Override
    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
        System.out.println(value.toString()); //For some reason this prints Wed Jul 23 02:00:00 CEST 2014 when inputting 23-07-2014
        DateTime date = new DateTime(value.toString());
        long dueDateMillis = date.getMillis();
        long oneDayMillis = 86400000;
        Calendar tomorrowMidnight = new GregorianCalendar();
        // reset hour, minutes, seconds and millis
        tomorrowMidnight.set(Calendar.HOUR_OF_DAY, 0);
        tomorrowMidnight.set(Calendar.MINUTE, 0);
        tomorrowMidnight.set(Calendar.SECOND, 0);
        tomorrowMidnight.set(Calendar.MILLISECOND, 0);
        tomorrowMidnight.add(Calendar.DAY_OF_MONTH, 1);
        if (dueDateMillis + oneDayMillis < tomorrowMidnight.getTimeInMillis()) {
            throw new ValidatorException(new FacesMessage("You can not have something repaired before tomorrow!"));
        }

    }

现在我不明白的是它为什么不以转换后的格式打印(dd-MM-yyyy),即使那时我也不在乎,只要我得到正确的毫秒数。 但是,DateTime构造函数然后抛出一个异常,即日期格式无效。

我也尝试过使用SimpleDateFormat,但没有运气。

2 个答案:

答案 0 :(得分:0)

转换器它会在页面上显示这种格式的日期(在jsp / html页面中)。它的作用是将字符串中的日期转换为dd-mm-yyyy格式。在validate函数中传递calue时,它不会以dd-MM-yyyy格式转换为字符串。它是一个日期,dueDate是一个日期,所以通过打印value.toString()只是将日期值转换为字符串。所以对象是一个日期,只需通过强制转换为Date就可以了。如果你想在代码中以dd-MM-yyyy的格式打印它,试试这个

Date date = (Date) value;
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
String strDate = sdf.format(date);
System.out.println(strDate );

答案 1 :(得分:-1)

@FacesValidator("validator.dateValidator")
public class DateValidator implements Validator, ClientValidator {
    final static String DATE_FORMAT = "dd-MM-yyyy";
    public DateValidator() {
    }
    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
        if (value == null || StringUtils.isEmpty((String) value.toString())) {
            return;
        }       
        SimpleDateFormat objDf = new SimpleDateFormat(DATE_FORMAT);
        objDf.setLenient(false);

        try {
            try {           
        Date data = new Date();
        data.setDate(data.getDate() + 1);
        if(objDf.parse(value.toString()).before(data)){
            ((UIInput) component).setValid(false);
            throw new ValidatorException(new FacesMessage("You can not have something repaired before tomorrow!"));
        }
    } catch (ParseException e) {

        ((UIInput) component).setValid(false);
        throw new ValidatorException(new FacesMessage(MessageUtils.ALERTA, "Data informada não Válida!", ""));

    }       
        } catch (ParseException e) {            
             throw new ValidatorException(new FacesMessage("Invalid Date!"));
        }
    }
    public Map<String, Object> getMetadata() {
        return null;
    }
    public String getValidatorId() {
        return "validator.dateValidator";
    }
}