In this blog, we are going to see how to validate a mobile number with 10 digits in Angular 2/4/5/8 using Pattern Validation. In this case, I have an input text in an Angular form, which validates if a number has 10 digits or not, and accepts only numbers.
Angular provides the PatternValidator directive that adds pattern validator to any control. We use regex as an attribute value.
app.component.html
- <form #userForm="ngForm" (ngSubmit)="onFormSubmit(userForm)">
- <table>
- <tr>
- <td>Mobile Number:</td>
- <td>
- <input name="mobileNumber" [ngModel]="user.mobileNumber" [pattern]="mobNumberPattern" #mobNumber="ngModel">
- <div *ngIf="mobNumber.errors && userForm.submitted && !isValidFormSubmitted" [ngClass] = "'error'">
- <div *ngIf="mobNumber.errors.pattern">
- Mobile number not valid.
- </div>
- </div>
- </td>
- </tr>
-
- <tr>
- <td colspan="2">
- <button>Submit</button>
- </td>
- </tr>
- </table>
- </form>
app.component.ts
- import { Component } from '@angular/core';
- import { NgForm } from '@angular/forms';
-
- @Component({
- selector: 'app-root',
- templateUrl: './app.component.html',
- styleUrls: ['./app.component.css']
- })
- export class AppComponent {
- title = 'FormValidation';
- mobNumberPattern = "^((\\+91-?)|0)?[0-9]{10}$";
- isValidFormSubmitted = false;
- user = new User();
-
-
- onFormSubmit(form: NgForm) {
- this.isValidFormSubmitted = false;
- if (form.invalid) {
- return;
- }
- this.isValidFormSubmitted = true;
- form.resetForm();
- }
- }
-
- export class User {
- mobileNumber ?: string;
- }
Output
That's it. You have seen how to validate a mobile number with 10 digits in Angular 2/4/5/8 using Pattern Validator.