Java regular expressions for reliable input validation
Every checkout, booking form and public API accepts untrusted text. Australian online retailers and fintech apps need dependable checks before those values reach services or databases.
Java’s Pattern and Matcher classes provide compact syntax for validating shapes such as postcodes, dates and email addresses. The patterns remain readable when they are small, named and covered by tests.
This guide to Java regular expressions for input validation shows where regex fits, how to apply it in Spring, and why syntax checks must sit beside business rules and security controls.
Why validation belongs at the boundary
Treat every HTTP request, JSON payload, command-line argument and form submission as untrusted. Validate required values and their format at the boundary so malformed data fails quickly with a useful error.
Validation should complement, not replace, database constraints and domain checks. A regex can recognise the shape of an account number, but it cannot determine whether the account exists or belongs to the customer.
Core syntax for useful patterns
Regular expressions use anchors (^ and $), character classes (\d, \w and \s), quantifiers (+, ? and {m,n}), groups and alternation. In Java string literals, every backslash must be doubled, so \d becomes \\d in source code.
Pattern code = Pattern.compile("^[A-Z]{2}\\d{4}$");
Matcher matcher = code.matcher("AB1234");
boolean valid = matcher.matches();
Groups capture useful pieces, while a non-capturing group (?:...) organises alternatives without adding a numbered value. Escaping literal metacharacters such as . or + prevents them from being interpreted as regex operators.
Matching and normalising input in Java
Compile a Pattern once for frequently used expressions, then create a Matcher for each value. Matcher.matches() checks the entire input, whereas find() can succeed on a matching substring and is easy to misuse.
private static final Pattern AU_MOBILE =
Pattern.compile("^(\\+61|0)4\\d{8}$");
private static boolean validMobile(String raw) {
if (raw == null) {
return false;
}
String value = raw.replaceAll("[\\s()-]", "");
return AU_MOBILE.matcher(value).matches();
}
Null needs an explicit policy. For values where whitespace is insignificant, trim first; for mobile numbers, remove agreed separators before matching. Keep this normalisation visible in one helper rather than scattering replacements through controllers.
Common fields and dependable rules
A rough email pattern can reject obvious mistakes, but it cannot prove that an address exists or fully implement email standards. Use a dedicated email validator for production rules and keep a simple shape check only when needed.
private static final Pattern EMAIL_SHAPE =
Pattern.compile("^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$");
Names also deserve care. Australia includes many cultures, scripts and family-name conventions, so avoid \w-based name rules that exclude valid Unicode letters. Permit the punctuation users genuinely need, and use length limits plus password guidance rather than a single complexity regex.
Australian formats and business context
Australian users commonly read dates as DD/MM/YYYY. Parse them with DateTimeFormatter and strict resolver settings instead of accepting several ambiguous formats, especially when ordering events in systems used in Sydney, Melbourne and Brisbane.
Contact fields often use +61 for the country code and omit the leading zero for mobile numbers. Domain fields may contain .com.au as well as .com, .net.au or a direct .au domain, so a hard-coded suffix list can reject legitimate addresses.
Local e-commerce, banking and software teams must also account for the Privacy Act 1988 and the Spam Act 2003. Correctly formed fields support those duties, but regex cannot replace consent records, privacy notices, access controls or secure storage.
Spring validation for real applications
Spring applications can apply Jakarta Bean Validation annotations to request objects. Use @Valid on the controller argument, @NotBlank for required strings and @Pattern for a constrained syntax; map violations into a clear 400 response.
public class CustomerRequest {
@NotBlank
@Pattern(regexp = "^(\\+61|0)4\\d{8}$")
private String mobile;
}
The annotation is one layer, not the whole policy. Keep service-level checks for relationships such as postcode and suburb, and never trust hidden HTML fields or client-side validation. Shared domain rules should work outside controllers as well.
A layered validation workflow
A dependable workflow separates shape, meaning and safety. Bound input lengths and avoid nested unbounded quantifiers, because hostile strings can otherwise cause excessive backtracking in a public Java endpoint.
- Reject null or blank required values with
@NotBlankand set sensible@Sizelimits. - Normalise phone, date and case formats explicitly before matching them.
- Compile reusable
Patternconstants and preferMatcher.matches()for whole-value checks. - Test valid values, malformed input, boundary lengths and adversarial strings in automated tests.
- Use parameterised SQL, output encoding and dedicated libraries for complex or checksummed identifiers.
Together, these checks reject malformed input early while preserving clear application rules and protection against injection.