Regex tester · Guide

Regex Tester Angular: Validators and Patterns in Angular Forms

Angular regex questions are almost always about `Validators.pattern`, which quietly rewrites your pattern before using it. Knowing what it does explains why a pattern that works in a tester rejects valid input.

pattern anchors your regex

Validators.pattern wraps a string pattern in ^ and $, so the whole value must match. A pattern intended as a search becomes a full-string requirement:

TypeScript
// these are equivalent — Angular adds the anchors
Validators.pattern('[a-z]+')
Validators.pattern('^[a-z]+$')

// pass a RegExp to avoid the rewrite
Validators.pattern(/[a-z]+/)

A string is anchored; a RegExp object is used as-is. That inconsistency is the source of most "my Angular pattern rejects valid input" reports.

A custom validator

When you need a specific error key or extra logic, write the validator directly:

TypeScript
export function slugValidator(): ValidatorFn {
  const re = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
  return (control: AbstractControl): ValidationErrors | null =>
    !control.value || re.test(control.value) ? null : { slug: true };
}

Return null for empty values and let Validators.required handle presence — combining the two concerns in one validator makes both harder to reuse.

Never keep a g flag on a validator regex: test() becomes stateful through lastIndex and the validator will pass and fail alternately.

Template-driven forms

The pattern attribute in a template is the HTML5 one, which is also implicitly anchored and is passed as a string — so the same rules apply.

Client-side validation is a usability feature, never a security control. Any pattern in the browser is advisory; validate the same rule on the server, where the user cannot edit it.

Frequently asked questions

Why does Validators.pattern reject a valid substring match?

String patterns are automatically anchored with ^ and $. Pass a RegExp object if you do not want that.

Can I use flags with Validators.pattern?

Only by passing a RegExp object. Avoid the g flag — it makes test() stateful.

Is client-side regex validation enough?

No. It improves the user experience; the server must enforce the same rule.

Ready to try it?

Open the free browser-based Regex tester and apply what you just read — no sign-up, runs locally.

Open the Regex tester tool