Validate date with regex

Whether you are validating an input field or posting a date to a service this snippet will show how to validate a date with a regular expression. Below will validate the date is MM-DD-YYYY so depending on your date pattern you will need to adjust the regular expression.

Straight up Java

@Test
public void validate_date_regex() {

    String date = "01-01-2016";
    String datePattern = "\d{1,2}-\d{1,2}-\d{4}";

    assertTrue(date.matches(datePattern));
}