Java | Date format validation using Regex
We use java.util.regex.Pattern.compile(String regex) method which compiles the given regular expression into a pattern. Here regex is the expression to be compiled.
// Java program to check if given date is // valid or not. import java.util.regex.Matcher; import java.util.regex.Pattern; public class GeeksforGeeks { // Returns true if d is in format // /dd/mm/yyyy public static boolean isValidDate(String d) { String regex = "^(1[0-2]|0[1-9])/(3[01]" + "|[12][0-9]|0[1-9])/[0-9]{4}$"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher((CharSequence)d); return matcher.matches(); } public static void main(String args[]) { System.out.println(isValidDate("10/12/2016")); System.out.println(isValidDate("10/02/18")); } } |
chevron_right
filter_none
Output:
true false
More ways to validate a date :
- SimpleDateFormat class. We can use parse method of this class to validate the date.
- Writing our own method to check if a date is valid.
Recommended Posts:
- DateFormat format(Date obj) method in Java
- Program to Convert Milliseconds to a Date Format in Java
- Java | Removing whitespaces using Regex
- Regex Boundary Matchers in Java
- Check if a string contains only alphabets in Java using Regex
- Count occurrences of a given character using Regex in Java
- Extracting each word from a String using Regex in Java
- Get the first letter of each word in a string using regex in Java
- Format Specifiers in Java
- Java String format() with examples
- LocalDate format() method in Java
- LocalDateTime format() method in Java
- YearMonth format() method in Java
- OffsetTime format() method in Java with examples
- ChronoZonedDateTime format() method in Java with Examples
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



