Validate date formats in Java using regular expressions
How far a regex can go in validating Java date strings, where it falls short, and how to combine a pattern check with java.time strict parsing.
The short answer
A regular expression is a good fit for checking that a string has the shape of a date, such as four digits, a hyphen, two digits, a hyphen and two digits. It cannot reliably tell you whether that string is a real calendar date. In Java, the dependable approach is a regex for shape, if you need one, followed by a strict parse with java.time to confirm the date exists.
A regex alone is enough when shape is all you need. Examples include filtering log lines, highlighting candidate dates in text, or pulling date-like substrings out of a larger document. It is not enough when the value will be stored, compared or used in calculations. In those cases, a string like 2023-02-30 has to be rejected, and a readable regex will not catch it.
Sometimes you can skip the regex entirely. For plain ISO dates, a strict java.time formatter already rejects most malformed input on its own. The regex adds value in two situations: when you want to pin the year to exactly four unsigned digits, and when you need to find dates inside other text rather than validate a whole field.
What a regex check actually does
Matching never modifies the input. It returns a yes or no, or a match position, against the string exactly as it is stored. Invisible characters, lookalike punctuation and non-ASCII digits all count. This matters for pasted input, which is covered below.
The word 'format' has two meanings in Java date handling, and they are easy to confuse. A regular expression is one kind of pattern. A date-time pattern string such as uuuu-MM-dd, used by DateTimeFormatter or the older SimpleDateFormat, is a different syntax with different rules. In a date-time pattern, MM means month and mm means minutes. Neither meaning applies inside a regex.
How you call the regex changes what it checks.
- String.matches() and Matcher.matches() succeed only if the entire input matches, so no ^ or $ anchors are needed.
- Matcher.find() succeeds if the pattern appears anywhere. With an unanchored pattern, abc2024-01-15xyz will pass.
- By default, Java's $ also matches just before a final line terminator. An anchored pattern used with find() can therefore accept a trailing newline. Use matches() or \z if that matters.
- By default, \d matches only ASCII 0–9. With the UNICODE_CHARACTER_CLASS flag, it also matches digits from other scripts.
Shape versus calendar validity
A typical ISO pattern restricts the month to 01–12 and the day to 01–31. It does not account for month length or leap years. Patterns that try to encode those rules exist, but they are long and hard to review, and mistakes in them are easy to miss. Calendar validity is better handled by a date library.
| Input | Shape regex (ISO, as in the example below) | Strict uuuu-MM-dd parse |
| 2024-02-29 | passes | valid (leap year) |
| 2023-02-29 | passes | rejected |
| 2023-02-30 | passes | rejected (a SMART formatter would instead adjust it to 2023-02-28) |
| 2024-13-01 | fails | rejected |
| 2024-1-5 | fails (no zero padding) | rejected (MM and dd expect two digits) |
| 2024-01-15 followed by a space | fails with matches() | rejected |
| 2024–01–15 with en dashes | fails | rejected |
The outcomes in this table follow from Java's documented behavior. They are not the results of a recorded test run. Add these cases to your own unit tests and confirm them on your JDK version.
A combined approach
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.format.ResolverStyle;
import java.util.regex.Pattern;
public final class DateValidator {
private static final Pattern ISO_SHAPE =
Pattern.compile("\\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\\d|3[01])");
private static final DateTimeFormatter STRICT_ISO =
DateTimeFormatter.ofPattern("uuuu-MM-dd")
.withResolverStyle(ResolverStyle.STRICT);
public static boolean isValid(String input) {
if (input == null || !ISO_SHAPE.matcher(input).matches()) {
return false;
}
try {
LocalDate.parse(input, STRICT_ISO);
return true;
} catch (DateTimeParseException e) {
return false;
}
}
}
Two details in this code are easy to get wrong.
- Use uuuu, not yyyy, together with ResolverStyle.STRICT. The letter y means year-of-era, and a strict resolver needs an era to resolve it. Without one, otherwise valid dates fail to parse.
- DateTimeFormatter.ofPattern defaults to the SMART resolver, which can silently adjust an out-of-range day instead of rejecting it. If you need rejection, set STRICT explicitly. LocalDate.parse(text) with no formatter uses ISO_LOCAL_DATE, which is already strict.
Avoid SimpleDateFormat in new code. If you are maintaining code that already uses it, call setLenient(false), and do not share one instance across threads, because it is not thread-safe.
Other formats and the meaning problem
A day-first pattern such as (0[1-9]|[12]\d|3[01])/(0[1-9]|1[0-2])/\d{4} is as easy to write as the ISO one. The difficulty is meaning, not syntax. A string like 03/04/2025 matches both day-first and month-first patterns. No regex can tell you which one the user intended. Decide on one format, state it to the user, and parse with the corresponding DateTimeFormatter pattern.
If you must accept several formats, try each strict formatter in a fixed order. Then document which interpretation wins for ambiguous input. Trying patterns in order does not remove the ambiguity. It only makes the outcome consistent.
Pasted and shared input
Input copied from documents, spreadsheets, chat apps or web pages can look correct but contain different characters. Common cases include:
- En dashes, minus signs or non-breaking hyphens in place of the ASCII hyphen.
- Fullwidth or other non-ASCII digits.
- Non-breaking spaces before or after the value. String.trim() and String.strip() do not remove these, because Character.isWhitespace excludes non-breaking spaces.
- Zero-width characters or a byte-order mark at the start of the value.
Choose a policy and apply it consistently: either reject such input with a clear message, or normalize it before validating. Normalizer with NFKC converts fullwidth digits to ASCII and non-breaking spaces to regular spaces. It does not convert dashes to hyphens and does not remove zero-width characters, so those need explicit replacement if you choose to normalize.
Turning on UNICODE_CHARACTER_CLASS so the regex accepts non-ASCII digits is usually a mistake if a strict parse follows. The regex will pass input that the default DateTimeFormatter parse is unlikely to accept, so the two checks disagree. Normalize first instead, or keep \d ASCII-only.
Readable error messages
Validation is only usable if people can fix what it rejects. State the expected format in visible text next to the field, with a concrete example such as 'Use YYYY-MM-DD, for example 2025-03-14'. A placeholder alone is not enough, because it disappears once the user starts typing. Where possible, say whether the problem is the shape or the date itself; 'February 30 does not exist' is easier to act on than 'Invalid format'.
How a specific screen reader or browser date control presents these messages was not tested here. Verify that in the environments you support.
Gaps in this review
No benchmarks, test logs or environment-specific results were supplied. The behavior described here comes from Java's documented regex and java.time APIs. Before relying on any edge case, especially resolver behavior, year handling beyond four digits and non-ASCII input, confirm it with unit tests on the JDK you deploy.