Javafx Datepicker validation

故事扮演 提交于 2019-12-07 04:07:25

问题


we tried to validate a javafx datepicker. So we use:

if (fromDatePicker.getValue() == null) {
        sb.append("No valid from date!\n");
    } else {
        System.out.println(fromDatePicker.getValue().toString());
        if (!DateUtil
                .validEnglishDate(fromDatePicker.getValue().toString())) {
            sb.append("No valid from date. Use the format yyyy-MM-dd.\n");
        }
    }

But at the moment it's impossible to get an invalid Date with the datepicker, because all invalid date's are changed to the start value. So we asked us is it possible to get an invalid Date with the javafx datepicker?

***** EDIT *****

Example: we have the following datepicker: DatePicker[2015-05-12] now we entered "fjdfk" in the DatePicker so we have: DatePicker[fjdfk] on save the data's the datepicker changes automatical to DatePicker[2015-05-12]


回答1:


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>)



来源:https://stackoverflow.com/questions/28432576/javafx-datepicker-validation

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