Regex date format validation on Java

Regex date format validation on Java

Asked on December 28, 2018 in Java.
Add Comment


  • 5 Answer(s)

    Here is the expression, Try to do this.

    ^\d{4}-\d{2}-\d{2}$
    

    like,

    if (str.matches("\\d{4}-\\d{2}-\\d{2}")) {
       ...
    }
    

    The anchors ^ means beginning of the string and $ means end of the string are present inferred , when we deal with matches method.

    Answered on December 28, 2018.
    Add Comment

    The SimpleDateFormat class can be used for built to do something . We need more than one regex for example “9999-99-00” is not a valid date.Even it is more heavy weight it is comprehensive.

    The example code is,

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
     
    boolean isValidDate(string input) {
         try {
              format.parse(input);
              return true;
         }
         catch(ParseException e){
              return false;
         }
    }
    
    Answered on December 28, 2018.
    Add Comment

    The following code can able to do the regex.  “^((19|20)\\d\\d)-(0?[1-9]|1[012])-(0?[1-9]|[12][0-9]|3[01])$”  and also it is deal with valid formats and valid dates. That means it is checks that and one thing is it will not validate the correct days of the month which means. leap year.

    String regex = "^((19|20)\\d\\d)-(0?[1-9]|1[012])-(0?[1-9]|[12][0-9]|3[01])$";
     
    Assert.assertTrue("Date: matched.", Pattern.matches(regex, "2011-1-1"));
    Assert.assertFalse("Date (month): not matched.", Pattern.matches(regex, "2011-13-1"));
    
    Answered on December 28, 2018.
    Add Comment

    Java date validation regex – match “dd/mm/yyyy” with required leading zeros. The regular expression forvalidating date format dd/mm/yyyy . Feel free to use and edit above regular expressions for date validation to suit your needs.

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    
    boolean isValidDate(string input) {
         try {
              format.parse(input);
              return true;
         }
         catch(ParseException e){
              return false;
         }
    }
    Answered on January 16, 2019.
    Add Comment

    This will do it regex: "^((19|20)\\d\\d)-(0?[1-9]|1[012])-(0?[1-9]|[12][0-9]|3[01])$" This will take care of valid formats and valid dates. It will not validate the correct days of the month i.e. leap year.

    String regex = "^((19|20)\\d\\d)-(0?[1-9]|1[012])-(0?[1-9]|[12][0-9]|3[01])$";
    
    Assert.assertTrue("Date: matched.", Pattern.matches(regex, "2011-1-1"));
    Assert.assertFalse("Date (month): not matched.", Pattern.matches(regex, "2011-13-1"));

     

     

    Answered on January 16, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.