Open In App

How to Check Whether the Date is in the Proper Format Using Regex?

Regex is a very interesting way to search, test, and match for patterns in a String that the user provides. Regex stands for Regular Expressions. Using regex is in application forms, where the application checks whether the date entered by the user is in the valid format or not. An error message is displayed when the user types the wrong format of the date that the evaluator expects.

In this article, we will discuss how to Check whether the given date is in the proper format or not.



Example to check the proper format of the date:

Input 1: date = “02-08-2003”
Output 1: VALID Date Entered

Input 2: date= “02.8.23”
Output 2: INVALID Date Entered



Java Program to Check the Validity of the Date Format Using Regex

Below is the code implementation to validate the date:




// Java Program to check the validity
// Of the Date format using Regex
import java.util.regex.Matcher;
import java.util.regex.Pattern;
  
public class CheckDate {
  
    public static boolean dateChecker(String date) 
    {
        String regexPattern = "^\\d{4}-\\d{2}-\\d{2}$";
        
      // \\d is used to match the numbers from 0-9
      Pattern standardPattern = Pattern.compile(regexPattern);
        
      // standartPattern represents the compiled regexPattern
      Matcher match = standardPattern.matcher(date);
        
      // match takes true or false based on the match
      return match.matches();
    }
  
    public static void main(String[] args) {
        
        String Birth_date_Entered = "2003-02-08";
  
        if (dateChecker(Birth_date_Entered)) 
        {
            System.out.println(Birth_date_Entered+ " is in valid format");
        } else {
            System.out.println(Birth_date_Entered + " is not in valid format");
        }
    }
}

Output
2003-02-08 is in valid format


Explanation of the above Program:


Article Tags :