Angular Pattern Validation Example
March 05, 2020
This page will walk through Angular pattern validation example. Angular provides PatternValidator
Directive that adds the pattern validator to any controls marked with the pattern
attribute. We need to provide regex as attribute value. pattern
attribute is bound to Validators.pattern
. In our example we will perform pattern validation with formControl
, ngModel
, formControlName
, FormGroup
and FormBuilder
.
Angular 4 uses
novalidate
attribute by default in its form element at run time and hence while submitting form, HTML 5 validation will not work. If we are using Angular 2, we need to write novalidate
attribute in our form element to disable HTML 5 validation and use Angular form validation. Here in our example we will provide pattern validation for username, password, mobile number and email with Template-driven form as well as Reactive form. Now find the complete example step by step.
Contents
- Technologies Used
- Project Structure
- PatternValidator
- Pattern Validation with formControl
- Pattern Validation with ngModel
- Pattern Validation with formControlName
- Validators.pattern with FormBuilder
- Validators.pattern with FormGroup
- Example-1: Pattern Validation using Reactive Form
- Example-2: Pattern Validation using Template-driven Form
- Run Application
- References
- Download Source Code
Technologies Used
Find the technologies being used in our example.1. Angular 9.0.2
2. Angular CLI 9.0.3
3. Node.js 12.5.0
Project Structure
Find the project structure of our demo application.my-app | |--src | | | |--app | | | | | |--user.ts | | |--user-service.ts | | |--reactive-form.component.ts | | |--reactive-form.component.html | | |--template-driven-form.component.ts | | |--template-driven-form.component.html | | | | | |--app.component.ts | | |--app.module.ts | | | |--main.ts | |--index.html | |--styles.css | |--node_modules |--package.json
PatternValidator
PatternValidator
is an Angular Directive. It ads pattern
validator to any control that is using pattern
attribute. The value of pattern
will be a regex. According to given regex, validation will be performed. pattern
attribute can be used with formControl
, ngModel
and formControlName
. To work with FormGroup
and FormBuilder
we will get pattern
from Validators
by calling Validators.pattern
. PatternValidator
Directive has following selectors.
[pattern][formControlName] [pattern][formControl] [pattern][ngModel]
Pattern Validation with formControl
We will perform pattern validation withformControl
here. Suppose we have created an instance of FormControl
for user name as following.
username = new FormControl();
pattern
attribute with regex in following way.
<input [formControl]="username" pattern="^[a-z0-9_-]{8,15}$">
pattern
using Angular property binding. Suppose we have following component property for regex to validate user name.
unamePattern = "^[a-z0-9_-]{8,15}$";
<input [formControl]="username" [pattern]="unamePattern">
<div *ngIf="username.errors?.pattern"> User name not valid. </div>
Pattern Validation with ngModel
We will perform pattern validation withngModel
here. Suppose we have a regex to validate username as given below.
unamePattern = "^[a-z0-9_-]{8,15}$";
ngModel
, we will use pattern
attribute in following way.
<input name="username" [ngModel]="user.username" [pattern]="unamePattern" #uname="ngModel">
<div *ngIf="uname.errors?.pattern"> User name not valid. </div>
Pattern Validation with formControlName
We will perform pattern validation withformControlName
here. To understand it we are creating a form with FormBuilder
. We are also initializing a component property for regex.
unamePattern = "^[a-z0-9_-]{8,15}$"; userForm = this.formBuilder.group({ username: '', ------ })
userForm
is the instance of FormGroup
. Now we can use pattern
with formControlName
as given below.
<input formControlName="username" [pattern]="unamePattern">
FormGroup
we will create getter for that control.
get username() { return this.userForm.get('username'); }
<div *ngIf="username.errors?.pattern"> User name not valid. </div>
Validators.pattern with FormBuilder
We can useValidators.pattern
for pattern validation while creating form either by FormBuilder
or by FormGroup
. Here we will provide code snippet for FormBuilder
. Find the form for user created by FormBuilder
and also find the sample regex.
unamePattern = "^[a-z0-9_-]{8,15}$"; userForm = this.formBuilder.group({ username: ['', Validators.pattern(this.unamePattern)], ------ })
Validators.pattern
. Our HTML code will be as follows.
<input formControlName="username">
get username() { return this.userForm.get('username'); }
<div *ngIf="username.errors?.pattern"> User name not valid. </div>
Validators.pattern with FormGroup
We will provide pattern validation withFormGroup
here. We will create a user form by using FormGroup
. We will create a user name control using FormControl
and pass Validators.pattern
to it. We will also create a component property for regex.
unamePattern = "^[a-z0-9_-]{8,15}$"; userForm = new FormGroup({ username: new FormControl('', Validators.pattern(this.unamePattern)), ------ })
<input formControlName="username">
get username() { return this.userForm.get('username'); }
<div *ngIf="username.errors?.pattern"> User name not valid. </div>
Example-1: Pattern Validation using Reactive Form
user.tsexport class User { username: string; password: string; mobileNumber: string; email: string; }
import { Component, OnInit } from '@angular/core'; import { FormControl, FormBuilder, Validators } from '@angular/forms'; import { UserService } from './user-service'; import { User } from './user'; @Component({ selector: 'app-reactive', templateUrl: './reactive-form.component.html' }) export class ReactiveFormComponent implements OnInit { unamePattern = "^[a-z0-9_-]{8,15}$"; pwdPattern = "^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s).{6,12}$"; mobnumPattern = "^((\\+91-?)|0)?[0-9]{10}$"; emailPattern = "^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$"; isValidFormSubmitted = null; userForm = this.formBuilder.group({ username: ['', [Validators.required, Validators.pattern(this.unamePattern)]], password: ['', [Validators.required, Validators.pattern(this.pwdPattern)]], mobileNumber: ['', Validators.pattern(this.mobnumPattern)], email: ['', Validators.pattern(this.emailPattern)], }); constructor(private formBuilder:FormBuilder, private userService: UserService) { } ngOnInit() { } onFormSubmit() { this.isValidFormSubmitted = false; if (this.userForm.invalid) { return; } this.isValidFormSubmitted = true; let user: User = this.userForm.value; this.userService.createUser(user); this.userForm.reset(); } get username() { return this.userForm.get('username'); } get password() { return this.userForm.get('password'); } get mobileNumber() { return this.userForm.get('mobileNumber'); } get email() { return this.userForm.get('email'); } }
<h3>Reactive Form</h3> <p *ngIf="isValidFormSubmitted && userForm.pristine" [ngClass] = "'success'"> Form submitted successfully. </p> <form [formGroup]="userForm" (ngSubmit)="onFormSubmit()"> <table> <tr> <td>User Name: </td> <td> <input formControlName="username"> <div *ngIf="username.errors && isValidFormSubmitted != null && !isValidFormSubmitted" [ngClass] = "'error'"> <div *ngIf="username.errors.required"> User name required. </div> <div *ngIf="username.errors.pattern"> User name not valid. </div> </div> </td> </tr> <tr> <td>Password: </td> <td> <input type="password" formControlName="password"> <div *ngIf="password.errors && isValidFormSubmitted != null && !isValidFormSubmitted" [ngClass] = "'error'"> <div *ngIf="password.errors.required"> Password required. </div> <div *ngIf="password.errors.pattern"> Password not valid. </div> </div> </td> </tr> <tr> <td>Mobile Number: </td> <td> <input formControlName="mobileNumber"> <div *ngIf="mobileNumber.errors && isValidFormSubmitted != null && !isValidFormSubmitted" [ngClass] = "'error'"> <div *ngIf="mobileNumber.errors.pattern"> Mobile number not valid. </div> </div> </td> </tr> <tr> <td>Email: </td> <td> <input formControlName="email"> <div *ngIf="email.errors && isValidFormSubmitted != null && !isValidFormSubmitted" [ngClass] = "'error'"> <div *ngIf="email.errors.pattern"> Email not valid. </div> </div> </td> </tr> <tr> <td colspan="2"> <button>Submit</button> </td> </tr> </table> </form>
import { Injectable } from '@angular/core'; import { User } from './user'; @Injectable() export class UserService { createUser(user: User) { console.log('User Name: ' + user.username); console.log('Password: ' + user.password); console.log('Mobile Number: ' + user.mobileNumber); console.log('Email: ' + user.email); } }
Example-2: Pattern Validation using Template-driven Form
template-driven-form.component.tsimport { Component, OnInit } from '@angular/core'; import { NgForm } from '@angular/forms'; import { UserService } from './user-service'; import { User } from './user'; @Component({ selector: 'app-template', templateUrl: './template-driven-form.component.html' }) export class TemplateDrivenFormComponent implements OnInit { unamePattern = "^[a-z0-9_-]{8,15}$"; pwdPattern = "^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s).{6,12}$"; mobnumPattern = "^((\\+91-?)|0)?[0-9]{10}$"; emailPattern = "^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$"; isValidFormSubmitted = false; validateEmail = true; user = new User(); constructor(private userService: UserService) { } ngOnInit() { } onFormSubmit(form: NgForm) { this.isValidFormSubmitted = false; if (form.invalid) { return; } this.isValidFormSubmitted = true; this.user = form.value; this.userService.createUser(this.user); this.user = new User(); form.resetForm(); } }
<h3>Template-driven Form</h3> <p *ngIf="isValidFormSubmitted" [ngClass] = "'success'"> Form submitted successfully. </p> <form #userForm="ngForm" (ngSubmit)="onFormSubmit(userForm)"> <table> <tr> <td>User Name:</td> <td> <input name="username" [ngModel]="user.username" required [pattern]="unamePattern" #uname="ngModel"> <div *ngIf="uname.errors && userForm.submitted && !isValidFormSubmitted" [ngClass] = "'error'"> <div *ngIf="uname.errors.required"> User name required. </div> <div *ngIf="uname.errors.pattern"> User name not valid. </div> </div> </td> </tr> <tr> <td>Password:</td> <td> <input name="password" type="password" [ngModel]="user.password" required [pattern]="pwdPattern" #pwd="ngModel"> <div *ngIf="pwd.errors && userForm.submitted && !isValidFormSubmitted" [ngClass] = "'error'"> <div *ngIf="pwd.errors.required"> Password required. </div> <div *ngIf="pwd.errors.pattern"> Password not valid. </div> </div> </td> </tr> <tr> <td>Mobile Number:</td> <td> <input name="mobileNumber" [ngModel]="user.mobileNumber" [pattern]="mobnumPattern" #mobnum="ngModel"> <div *ngIf="mobnum.errors && userForm.submitted && !isValidFormSubmitted" [ngClass] = "'error'"> <div *ngIf="mobnum.errors.pattern"> Mobile number not valid. </div> </div> </td> </tr> <tr> <td>Email:</td> <td> <input name="email" [ngModel]="user.email" [pattern]="emailPattern" #userEmail="ngModel"> <div *ngIf="userEmail.errors && userForm.submitted && !isValidFormSubmitted" [ngClass] = "'error'"> <div *ngIf="userEmail.errors.pattern"> User name not valid. </div> </div> </td> </tr> <tr> <td colspan="2"> <button>Submit</button> </td> </tr> </table> </form>
import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: ` <app-reactive></app-reactive> <app-template></app-template> ` }) export class AppComponent { }
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; import { ReactiveFormComponent } from './reactive-form.component'; import { TemplateDrivenFormComponent } from './template-driven-form.component'; import { UserService } from './user-service'; @NgModule({ imports: [ BrowserModule, FormsModule, ReactiveFormsModule ], declarations: [ AppComponent, ReactiveFormComponent, TemplateDrivenFormComponent ], providers: [ UserService ], bootstrap: [ AppComponent ] }) export class AppModule { }
table { border-collapse: collapse; } table, th, td { border: 1px solid black; } .error { color: red; } .success { color: green; }
Run Application
To run the application, find following steps.1. Download source code using download link given below on this page.
2. Use downloaded src in your Angular CLI application. To install Angular CLI, find the link.
3. Run ng serve using command prompt.
4. Now access the URL http://localhost:4200
When we enter invalid data and click on submit button, we will get following output.

User Name: concretepage Password: x2z@dG1 Mobile Number: 9812703058 Email: mahesh@gmail.com
References
PatternValidatorAngular QuickStart