Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javafx Datepicker validation

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]

like image 503
Andreas Avatar asked Sep 28 '22 19:09

Andreas


1 Answers

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

like image 53
Jules Sam. Randolph Avatar answered Oct 07 '22 19:10

Jules Sam. Randolph