Full Name Validation with Regex in Java
How a Unicode-aware Java regex for full names works, what normalization changes, where ASCII patterns reject real people, and when plain-text acceptance is the better choice.
A regex for name validation in Java can catch obvious junk such as digits, markup, line breaks and invisible control characters. It cannot tell you whether a name is real. The most common pattern found in tutorials allows only ASCII letters and spaces, and it rejects accents, apostrophes, hyphens and every non-Latin script. This review covers what a Unicode-aware pattern accepts, what normalization changes before matching, and how pasted or styled text behaves once it reaches your validator.
Is regex validation suitable for full names?
Regex validation suits names when you use it as a permissive check. Use it to reject input that cannot be a name, and do not use it to enforce what a name should look like. The main benefit is that one precompiled pattern blocks digits, symbols, control characters and bidirectional formatting characters before they reach storage or display. The tradeoff is that every rule you add will turn away some real person, so a strict pattern costs you users and gains little in data quality.
Plain-text acceptance is the better choice in several situations. It means accepting any nonblank text up to a length limit and escaping the text on output. Choose it when your audience is international, when the name is only shown back to the person or used in a greeting, or when a rejected sign-up costs more than an odd-looking record. Protection against injection belongs in output encoding and parameterized queries, not in a name regex.
What validation changes and what it leaves alone
Matching a pattern does not change the string. Several of the steps that usually surround validation do change it, and "reverse", "mirror" and "font" each mean different things depending on where the change happens. The distinctions below matter when you decide what to store.
- Validation: Pattern.matcher(name).matches() returns true or false. The characters stay exactly as entered.
- Canonical normalization (NFC): java.text.Normalizer combines a base letter and a separate combining accent, such as e followed by U+0301, into the single precomposed character é. The stored code points change and the visible text does not.
- Compatibility normalization (NFKC): this goes further. It maps styled mathematical letters, fullwidth forms and some ligatures to plain equivalents. Because it changes how stored text looks, it suits search and comparison keys better than the display name.
- CSS fonts and styling: these change appearance only. The stored text is untouched.
- Generated "Unicode fonts": generators that produce bold, script or double-struck text substitute entirely different code points. To Java these are new characters, not a styling of the original ones.
- Mirrored or reversed display: bidirectional override characters such as U+202E make text display in reverse order while the stored order stays the same. Upside-down text generators instead substitute look-alike letters such as ǝ and ɹ.
Why the usual ASCII pattern falls short
The pattern below appears often in search results for Java name validation. It accepts one or more runs of ASCII letters separated by single spaces.
private static final Pattern ASCII_NAME =
Pattern.compile("^[A-Za-z]+(?: [A-Za-z]+)*$");
This pattern rejects José, O'Brien, Jean-Luc and any name written in Chinese, Arabic, Cyrillic or Devanagari script. Swapping in \w does not fix it. In Java, \w means ASCII letters, digits and underscore unless you enable Pattern.UNICODE_CHARACTER_CLASS, and with that flag enabled it still admits digits and underscores, which do not belong in a name. Unicode property classes are the more precise tool here.
A Unicode-aware full name validator
The class below normalizes the input first and then matches it against a pattern built on Unicode letter and mark categories. A single name such as a mononym is accepted, so the pattern does not require both a first and a last name.
import java.text.Normalizer;
import java.util.regex.Pattern;
public final class FullNameValidator {
// A name part starts with a letter and may continue with letters or combining marks.
// Parts are joined by a space, a hyphen, a straight or curly apostrophe,
// or a period with an optional space. A trailing period allows suffixes such as "Jr.".
private static final Pattern FULL_NAME = Pattern.compile(
"^\\p{L}[\\p{L}\\p{M}]*(?:(?:\\. ?|[ '\\u2019-])\\p{L}[\\p{L}\\p{M}]*)*\\.?$");
private FullNameValidator() {
}
public static String normalize(String input) {
String composed = Normalizer.normalize(input, Normalizer.Form.NFC);
return composed.replaceAll("\\h+", " ").strip();
}
public static boolean isValid(String input) {
if (input == null) {
return false;
}
String name = normalize(input);
return !name.isEmpty() && FULL_NAME.matcher(name).matches();
}
}
- \p{L} matches any Unicode letter in any script. Each name part must begin with one, so a stray combining mark cannot start a part.
- \p{M} matches combining marks. These cover decomposed accents, and they are also required for scripts such as Devanagari, where vowel signs are mark characters rather than letters.
- The separator group accepts ". ", ".", a space, an apostrophe (straight U+0027 or curly U+2019) or a hyphen. Every separator is exactly one required unit, which keeps the repetition unambiguous and avoids the nested-quantifier backtracking that empty separators would cause.
- The hyphen sits at the end of the character class so that Java reads it as a literal character.
- matches() requires the whole string to match, so the ^ and $ anchors are redundant with it. They are kept so the pattern stays correct if someone later switches to find().
- Normalizer.Form.NFC composes accents before matching. \h collapses any run of horizontal whitespace, including the non-breaking space U+00A0, into one ordinary space. strip(), available since Java 11, trims Unicode whitespace, whereas trim() removes only characters at or below U+0020.
- The Pattern is compiled once as a static final field. Compiling inside isValid would rebuild it on every call.
Expected results for sample inputs
The outcomes below were worked out from the pattern logic and Unicode character categories. They were not observed in a recorded test run, so confirm each one with a parameterized unit test on your own JDK. The ASCII column assumes no normalization step, which matches how that pattern is usually deployed.
| Input | ASCII-only pattern | Unicode validator above |
| Jean-Luc Picard | Rejected (hyphen) | Accepted |
| Mary O'Brien | Rejected (apostrophe) | Accepted |
| Mary O’Brien (curly apostrophe) | Rejected | Accepted |
| José Álvarez (precomposed accents) | Rejected | Accepted |
| José with e followed by U+0301 | Rejected | Accepted (NFC composes it, and \p{M} would allow the mark anyway) |
| J. R. R. Tolkien | Rejected (periods) | Accepted |
| Martin Luther King Jr. | Rejected (period) | Accepted |
| 王小明 | Rejected | Accepted |
| Madonna (single name) | Accepted | Accepted |
| John, two spaces, Smith | Rejected | Accepted after whitespace is collapsed |
| John, non-breaking space, Smith | Rejected | Accepted after \h is collapsed |
| Smith, John | Rejected (comma) | Rejected (comma) |
| John Smith3 | Rejected | Rejected |
| Anna, zero-width space U+200B, Smith | Rejected | Rejected (U+200B is a format character) |
| Name containing U+202E right-to-left override | Rejected | Rejected |
| 𝐉𝐨𝐡𝐧 𝐒𝐦𝐢𝐭𝐡 (mathematical bold letters) | Rejected | Accepted, because these characters are in the letter category |
| Persian name containing zero-width non-joiner U+200C | Rejected | Rejected, which may be a false rejection |
Copying, pasting and sharing names
Most validation failures on real names come from invisible differences in pasted or auto-corrected text, not from what the person meant to type. Many keyboards and word processors replace a straight apostrophe with the curly U+2019, so a pattern that allows only one of them will reject names that look correct on screen. Text copied from web pages can carry non-breaking spaces or zero-width spaces. The normalize method handles the first case. Zero-width spaces are rejected, and you can strip U+200B before matching if your users paste from such sources often.
Be careful not to strip all invisible format characters in one sweep. The zero-width non-joiner U+200C and zero-width joiner U+200D carry meaning in some scripts, including Persian and several Indic scripts, and removing them can change how a name is spelled. The validator above rejects them. If you serve those communities, decide whether to allow the joiners, and test that decision with native speakers rather than assuming it is right.
Styled "Unicode font" text and upside-down text pass the validator because their characters really are letters. Bidirectional override characters do not pass, and that is the safer outcome. Those overrides can make stored text display in a different order than it is stored, which makes them useful for spoofing how a name appears to other users.
If you want to block styled letters, you have two options. One is to compare the input with its NFKC form and reject the name, or ask the user to retype it, when the two differ. The other is to store the NFC form as entered and use NFKC only for search keys. Rejecting on any NFKC difference also catches fullwidth letters and some ligatures that a person may have entered on purpose, so the first option is stricter than it may appear. Styled letters are distinct code points, so a search for the plain spelling will not find them unless you build a folded search key.
Accessibility and the error message
When a name is rejected, the error message has to tell the person what to change, in text, beside the field. A message such as "Names can contain letters, spaces, hyphens, apostrophes and periods" helps far more than "Invalid name". It also shows the user that the form accepts their spelling, so they do not feel pushed into anglicizing their name to get past it. Do not use color as the only signal that something is wrong.
How screen readers announce styled mathematical letters or upside-down look-alike characters was not tested for this review, and no documentation for any specific assistive technology was supplied. Do not assume such text will be read as the plain name it resembles. Wherever a name is displayed to other people or read aloud, the plain-text spelling is the reliable choice.
Length, storage and search
String.length() counts UTF-16 code units, not characters. A name containing supplementary characters, such as rarer CJK ideographs outside the Basic Multilingual Plane, reports a larger length than the number of characters it visibly contains. Use codePointCount(0, name.length()) when enforcing a limit tied to a database column defined in characters. Use java.text.BreakIterator.getCharacterInstance() when the limit should reflect what the user sees, since a letter followed by combining marks displays as one character. Set the upper bound generously and base it on your storage, not on assumptions about how long names usually are.
For duplicate detection or lookup, keep two values. The first is the display name, normalized to NFC and stored as entered. The second is a separate key built by applying NFKC and then toLowerCase(Locale.ROOT). This preserves the person's spelling while still letting the plain and styled variants of the same letters match. Case and accent folding rules vary by language, so treat the key as an aid to matching and never as proof of identity.
Requiring both a first and a last name
Many people have a single name, and the order of given name and family name differs across cultures. A single full-name field accepted as entered avoids both problems. If a process genuinely needs at least two parts, change the final * on the repeated group to +. Be aware that this still counts "Jean-Luc" as two parts, because a hyphen satisfies the separator, and it will reject mononyms outright. Splitting a full name into first and last name with a regex is unreliable for the same reasons. Ask for separate fields only if you truly need them, and label them by their purpose rather than by assumed order.
Gaps in this review
- No benchmark or performance measurement was run. The claim that the pattern avoids heavy backtracking is based on its structure, not on timing data.
- The sample outcomes were derived from Unicode categories and the pattern logic. They were not recorded from a test run on a specific JDK version.
- No screen reader or assistive technology was tested with styled or look-alike characters.
- The right policy for zero-width joiners in Persian and Indic names is still unresolved and needs input from native speakers.
- No data was available on how often real users enter each problem case, so the tradeoffs above are qualitative.