Validate numeric input with an Angular regex pattern
How Angular's pattern validator checks numeric input, which regex fits which kind of number, and where pasted text, Unicode digits and type="number" cause trouble.
Angular's pattern validator is a common way to make sure a form field contains only a number. It is simple to add, but its behavior depends on how the pattern is written, what kind of input element it is attached to, and what users actually type or paste. This review covers what the validator checks, which patterns suit which kinds of numbers, and where the approach breaks down.
Is a regex pattern the right tool for numeric validation?
For a narrow format that you can describe exactly, a pattern is usually a good fit. Examples include whole-number quantities, a fixed-length numeric code, or a price with at most two decimal places. The main benefit is precision: the pattern states exactly which characters, signs and decimal places are allowed, and Angular reports a single, predictable error when the value does not match.
The decisive tradeoff is strictness. A pattern rejects anything outside its character set, including input that a person would read as a valid number. Common cases are a thousands separator, a decimal comma, a leading space, or digits from another script.
A looser plain-text field is often the better choice in several situations: the audience writes numbers in different locale formats, the value is really an identifier such as a phone number, or the real goal is a numeric range. In those cases, accept free text, normalize it, parse it, and then validate the parsed result. For range checks, Validators.min and Validators.max on a parsed value say more clearly what you mean than a regex does.
What the pattern validator actually does
Despite the word "pattern," this is a check, not a transformation. Validators.pattern does not alter, reformat or strip any characters in the control's value. It tests the current value against a regular expression and either returns null (valid) or an error object under the key "pattern". That object contains the required pattern and the actual value. The stored value stays exactly as the user entered it. If you want to change the value itself, for example by trimming spaces or converting full-width digits, you need a separate step.
How you supply the pattern changes how it is applied:
- String pattern: Angular adds a leading ^ and a trailing $ if they are missing, so the whole value must match.
- RegExp object: used exactly as written, so you must include ^ and $ yourself, or a value like "12abc" can pass because it contains digits.
- RegExp with the g or y flag: test() remembers its position between calls (lastIndex), which can make the same value alternate between valid and invalid. Angular's documentation warns against these flags.
- Empty values: the pattern validator treats an empty value as valid. Add Validators.required if the field must be filled in.
Escaping is the most common source of silent bugs. Inside a TypeScript string literal, a single backslash before d is dropped, so the string '\d+' becomes 'd+' and matches the letter d. Either double the backslash in a string or use a regex literal. In a template attribute, a single backslash is kept as written.
import { Component } from '@angular/core';
import { FormControl, ReactiveFormsModule, Validators } from '@angular/forms';
@Component({
selector: 'app-quantity',
standalone: true,
imports: [ReactiveFormsModule],
templateUrl: './quantity.component.html',
})
export class QuantityComponent {
// Regex literal: anchors are required because Angular uses it as-is.
quantity = new FormControl('', [Validators.required, Validators.pattern(/^\d+$/)]);
// Equivalent string form: Angular adds ^ and $; the backslash must be doubled.
quantityFromString = new FormControl('', [Validators.required, Validators.pattern('\\d+')]);
}
<!-- Template-driven equivalent: one backslash is enough inside an attribute -->
<input name="quantity" ngModel required pattern="\d+">
Choosing a pattern for the kind of number you need
In JavaScript regular expressions, \d matches only the ASCII digits 0 through 9, even when the u flag is set. Every pattern below therefore rejects digits from other scripts unless you normalize the input first.
| Pattern | Intended values | Accepts | Rejects |
| ^\d+$ | Non-negative whole numbers | 0, 42, 042 | -3, 1.5, " 7" |
| ^(0|[1-9]\d*)$ | Whole numbers without leading zeros | 0, 250 | 007, -1 |
| ^-?\d+$ | Signed whole numbers | 15, -3 | +3, 3-, 1.0 |
| ^-?\d+(.\d{1,2})?$ | Up to two decimal places, dot separator | 3, 3.5, -0.25 | .5, 3., 3.125, 3,5 |
| ^\d{5}$ | Fixed-length numeric code | 02134 | 2134, 021345 |
The rejections in this table follow from how each pattern is written. They do not come from a test run. Check any pattern against your own list of expected and unexpected inputs before relying on it, because small details matter. For example, ".5" and "3." are numbers to most people but fail the decimal pattern above.
Why type="number" and a pattern work poorly together
Pairing a pattern with an input of type="number" often gives confusing results, for three reasons:
- Malformed input never reaches the pattern. When the browser cannot parse what was typed (for example "1e" or "--"), it reports an empty value. Angular then stores null, so the user sees a "required" error, or no error at all, instead of a pattern error.
- The validator sees a reformatted number. Angular's number value accessor stores a JavaScript number, and the regex test turns it back into a string. Trailing zeros disappear (1.50 becomes 1.5), and very large or very small values may turn into exponential notation, so a decimal-places pattern can pass or fail unexpectedly.
- The HTML pattern attribute does not apply. The native pattern attribute is defined only for text-like input types, not number. Angular's own pattern validator still runs, but you get no browser-level backup from it.
A more predictable setup is type="text" with inputmode="numeric" (or inputmode="decimal" when decimals are allowed). The control value then stays a string, the pattern tests exactly what the user typed, and supporting devices can still show a numeric keyboard. The tradeoff is that the value is a string, so you convert it to a number yourself, for example with Number(), when the form is submitted. Keyboard behavior varies by device and browser, and the evidence for this article includes no device testing.
Will pasted or shared numbers still validate?
Copy and paste is where strict patterns most often reject input that looks correct. Text copied from documents, spreadsheets, chat apps or web pages can carry characters that look like plain digits and signs but are different code points:
- Leading or trailing spaces, including non-breaking spaces
- Thousands separators such as 1,000 or 1 000
- Full-width digits such as 123, common in East Asian input methods
- Digits from other scripts, such as Arabic-Indic or Devanagari digits
- A typographic minus sign (U+2212) or an en dash instead of the ASCII hyphen-minus
- Invisible formatting characters, such as zero-width spaces or bidirectional marks, picked up from right-to-left text
Because the pattern validator does not change the value, each of these characters causes a pattern error. You have two options: tell the user exactly what is allowed, or normalize the value before it is validated or stored. Unicode NFKC normalization converts full-width digits to ASCII digits and changes some compatibility spaces to ordinary spaces. It does not convert Arabic-Indic or other native-script digits to ASCII, and it does not turn U+2212 into a hyphen-minus. Those characters need explicit mapping if you want to accept them.
normalizeQuantity(): void {
const raw = this.quantity.value ?? '';
const normalized = raw.normalize('NFKC').trim();
if (normalized !== raw) {
this.quantity.setValue(normalized);
}
}
Calling a method like this on blur gives a visible, predictable change: the user sees the corrected value in the field. Silently rewriting the value on every keystroke can move the cursor and make editing harder. Whichever approach you choose, normalize the value again on the server, since client-side validation can be bypassed.
Accessibility and error messages
Angular adds CSS classes such as ng-invalid and ng-touched to the control. These classes are visual hooks only. In plain Angular forms they do not tell assistive technology anything about the error. Set aria-invalid yourself, and link the error message to the input with aria-describedby, so screen reader users hear why the value was rejected.
<label for="qty">Quantity</label>
<input id="qty" type="text" inputmode="numeric"
[formControl]="quantity"
(blur)="normalizeQuantity()"
[attr.aria-invalid]="quantity.invalid && quantity.touched"
aria-describedby="qty-hint qty-error">
<p id="qty-hint">Whole numbers only, using digits 0 to 9.</p>
@if (quantity.touched && quantity.hasError('pattern')) {
<p id="qty-error">Enter a whole number without spaces, commas or decimals.</p>
}
Write the error message in plain words and describe what is allowed, rather than showing the regex or the requiredPattern value from the error object. A raw pattern means little to most readers and is awkward to hear read aloud. The @if block uses Angular's built-in control flow syntax; projects on older versions can use *ngIf instead.
Known gaps
This article describes documented Angular and JavaScript behavior and how the example patterns are constructed. It does not report scoped tests of specific browsers, mobile keyboards or screen readers, so how inputmode, number inputs and error announcements behave in a given environment should be checked directly. Locale-specific number formats, such as decimal commas, are not covered by any pattern here and need their own parsing strategy.