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]
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>)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With