Javafx Datepicker validation

坚强是说给别人听的谎言 提交于 2019-12-05 09:02:09

You could use the DatePicker#setConverter(StringConverter<LocalDate>) to catch any parse exception and warn the user in consequence. Here is a sample :

public class SecureLocalDateStringConverter extends StringConverter<LocalDate> {
    /**
     * The date pattern that is used for conversion. Change as you wish.
     */
    private static final String DATE_PATTERN = "dd/MM/yyyy";

    /**
    * The date formatter.
    */
    public static final DateTimeFormatter DATE_FORMATTER =
        DateTimeFormatter.ofPattern(DATE_PATTERN);

    private boolean hasParseError = false;

    public boolean hasParseError(){
        return hasParseError;
    }

    @Override
    public String toString(LocalDate localDate) {
       return DATE_FORMATTER.format(localDate);
    }

    @Override
    public LocalDate fromString(String formattedString) {

            try {
                LocalDate date=LocalDate.from(DATE_FORMATTER.parse(formattedString));
                hasParseError=false;
                return date;
            } catch (DateTimeParseException parseExc){
                hasParseError=true;
                return null;
            }
    }

}

From your control, you'll just have to call converter#hasParseError(), converter being the one you set with DatePicker#setConverter(StringConverter<LocalDate>)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!