Friday, September 5, 2025
HomeLanguagesJavaJava | Date format validation using Regex

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 Lazyroar {
  
    // 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"));
    }
}


Output:

true
false

More ways to validate a date :

  1. SimpleDateFormat class. We can use parse method of this class to validate the date.
  2. Writing our own method to check if a date is valid.
RELATED ARTICLES

Most Popular

Dominic
32264 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6634 POSTS0 COMMENTS
Nicole Veronica
11801 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11863 POSTS0 COMMENTS
Shaida Kate Naidoo
6750 POSTS0 COMMENTS
Ted Musemwa
7025 POSTS0 COMMENTS
Thapelo Manthata
6701 POSTS0 COMMENTS
Umr Jansen
6718 POSTS0 COMMENTS