In: Computer Science
If I want to show an exception in JAVA GUI that checks if the date format is correct or the date doesn't exist, and if no input is put in how do I do that. For example if the date format should be 01-11-2020, and user inputs 11/01/2020 inside the jTextField it will show an error exception message that format is wrong, and if the user inputs an invalid date, it will print that the date is invlaid, and if the user puts no value inside the text box, it willl print an exception message that there needs to be a value.
Please help.
A date is valid if it satisfies following constraints.
For validating first constraint we are using Regular expressions and for second constraint setLenient() method of DateFormat class.
For example:
private static boolean isValidDate(String input) {
String formatString = "MM/dd/yyyy";
try {
SimpleDateFormat format = new SimpleDateFormat(formatString);
format.setLenient(false);
format.parse(input);
} catch (ParseException e) {
return false;
} catch (IllegalArgumentException e) {
return false;
}
return true;
}
public static void main(String[] args){
System.out.println(isValidDate("45/23/234")); // false
System.out.println(isValidDate("12/12/2111")); // true
}
The output will be false for first date in main function.
The output will be true for second date in main function.