Validate Angular forms with regular expressions
How Angular's pattern validator checks form input with regular expressions, where it fits, how string and RegExp patterns differ, and the Unicode, paste and accessibility limits to plan for.
What regex validation does in an Angular form
Angular checks a control's value against a regular expression through its built-in pattern validator. Reactive forms use it as Validators.pattern, and template-driven forms use it as the pattern attribute. If the value does not match, the control becomes invalid and gets a pattern error. If it matches, the error is removed.
The validator never edits the value. It is not a text transformation like reversing or restyling characters. The typed string, the model value and the submitted data stay exactly as the user entered them. Only the control's validity status and its errors object change. Trimming whitespace, uppercasing a code or stripping separators are separate steps that you have to write yourself.
Is regex validation the right fit for your field?
Regex validation is a good fit when a field has a fixed, describable shape. Its main benefit is immediate, declarative feedback with very little code. The main tradeoff is that a pattern checks only shape, not meaning. A strict pattern also rejects legitimate input that you did not anticipate.
- Good fits: postal codes, product or account codes, fixed-length numeric identifiers, slugs, simple username rules.
- Poor fits: whether a date actually exists (for example February 30), whether an email address can receive mail, personal names, free-form addresses, and anything that depends on other fields or server data.
- Use a custom or async validator instead when the rule needs logic, lookups or cross-field comparison.
Show users a plain-language description of the expected format, such as "five digits, optionally followed by a hyphen and four digits". Do not show them the regular expression. Client-side validation only improves the experience. The same rule must also be enforced on the server, because anyone can bypass browser-side checks.
Reactive forms: Validators.pattern
import { Component } from '@angular/core';
import { FormControl, ReactiveFormsModule, Validators } from '@angular/forms';
@Component({
selector: 'app-zip-field',
imports: [ReactiveFormsModule],
template: `
<label for="zip">ZIP code</label>
<input id="zip" [formControl]="zip" aria-describedby="zip-hint zip-error">
<p id="zip-hint">Five digits, optionally followed by a hyphen and four digits.</p>
@if (zip.touched && zip.hasError('pattern')) {
<p id="zip-error">That ZIP code is not in a recognized format.</p>
}
`,
})
export class ZipFieldComponent {
zip = new FormControl('', [
Validators.required,
Validators.pattern(/^\d{5}(-\d{4})?$/),
]);
}
The pattern validator skips empty values. An empty field therefore passes the pattern check. If the field is mandatory, add Validators.required alongside the pattern.
String patterns versus RegExp objects
Angular treats the two argument types differently. With a string, Angular adds a leading ^ and a trailing $ if they are missing, so the whole value has to match. With a RegExp object, Angular uses the expression exactly as written. An unanchored RegExp will accept any value that merely contains a match.
Validators.pattern('[A-Z]{2}\\d{4}') // tested as ^[A-Z]{2}\d{4}$
Validators.pattern(/[A-Z]{2}\d{4}/) // no anchors added: 'xxAB1234yy' passes
Validators.pattern(/^[A-Z]{2}\d{4}$/) // anchored explicitly: whole value must match
Automatic anchoring can mislead you when the pattern uses alternation. The string 'cat|dog' becomes ^cat|dog$. That expression accepts any value starting with cat or ending with dog. Wrap alternatives in a group, as in '(cat|dog)', so the anchors apply to the whole expression.
Avoid the g and y flags on a RegExp passed to the validator. With these flags, test() remembers its last position between calls. The same value can then pass on one check and fail on the next.
Template-driven forms: the pattern attribute
<input name="code" ngModel required pattern="[A-Z]{2}\d{4}" #code="ngModel">
@if (code.touched && code.errors?.['pattern']) {
<p>Use two capital letters followed by four digits, for example AB1234.</p>
}
A pattern written directly in an HTML attribute needs only a single backslash. The same pattern in a TypeScript string literal needs two, as in '\d'. Otherwise the backslash is consumed before Angular sees it. You can also bind the attribute to a component property with [pattern]="codePattern" and keep the expression in TypeScript.
Angular adds novalidate to forms by default. The browser's own pattern tooltip therefore does not appear, and Angular's validator and your error markup handle the feedback.
Reading the pattern error
When validation fails, the control's errors include a pattern entry with two properties. The first is requiredPattern: the anchored string for string inputs, or the expression's string form, slashes and flags included, for RegExp inputs. The second is actualValue, the value that failed. These are useful for debugging and logging. They are not suitable as user-facing messages.
Pasted input, Unicode and invisible characters
Text copied from documents, spreadsheets or chat apps often carries characters that look like what the pattern expects but are not. Examples include leading or trailing spaces, non-breaking spaces, curly quotes, full-width digits and zero-width characters. The validator tests the raw value. A pasted code that looks correct can still be rejected, and the user will have no obvious reason why.
Character classes also cause trouble. In JavaScript, \w and [A-Za-z] cover ASCII only, so names such as José or Zoë fail. An accented letter can arrive precomposed as one code point, or decomposed as a base letter plus a combining mark. A pattern that allows letters but not marks will reject the decomposed form.
Length quantifiers have a related problem. Without the u flag, quantifiers count UTF-16 code units, and many emoji use two of them. Even with the u flag, a single visible emoji such as a family or flag can be several code points. A quantifier like {1,20} is therefore not a reliable limit on visible characters.
// Letters and combining marks from any script, plus apostrophe, space and hyphen
Validators.pattern(/^[\p{L}\p{M}' -]+$/u)
Flags cannot be expressed in a string pattern. Unicode property escapes such as \p{L} therefore require a RegExp object with the u flag. If pasted input is common for a field, consider a small custom validator that normalizes before testing. You can apply the same normalization to the value before submitting it.
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';
export function normalizedPattern(re: RegExp): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
const value = control.value;
if (value == null || value === '') return null;
const normalized = String(value).normalize('NFC').trim();
return re.test(normalized)
? null
: { pattern: { requiredPattern: String(re), actualValue: value } };
};
}
Accessibility of validation feedback
Angular marks controls with CSS classes such as ng-invalid and ng-touched. Whether assistive technology conveys an error depends on your markup. Give each field a visible label and state the expected format in plain words before the user types. Link hint and error text to the input, for example with aria-describedby. Do not rely on color alone. A bare "invalid format" message, or a message quoting the regex, gives users nothing to act on.
No screen reader or browser test was supplied for this review, so announcement behavior in specific assistive technologies is not verified here. Test with the tools your users rely on.
Performance and security limits
Patterns with nested or overlapping quantifiers, such as (a+)+ or (\w|\d)*, can backtrack catastrophically on certain inputs and freeze the page while a user types. Keep patterns simple and anchored, and test them against long, nearly matching strings. A pattern on the client is not a security control. Repeat the validation on the server with the same intent.
Choosing an approach
| Approach | Anchoring | Flags | Best for |
| Validators.pattern with a string | Added automatically | Not supported | Simple ASCII formats in reactive forms |
| Validators.pattern with a RegExp | Your responsibility | Supported (avoid g and y) | Unicode-aware rules using the u flag |
| pattern attribute (template-driven) | Added automatically | Not supported | Simple formats in template-driven forms |
| Custom validator | Your responsibility | Any | Normalization, trimming, multi-step or cross-field logic |
What this review could not verify
No version-specific evidence, test results or measurements were provided. The behavior described here follows Angular's documented forms API and standard JavaScript regular expression semantics. Confirm it against the Angular version your project uses, especially if you use newer form APIs that may offer their own pattern validation.