Validate Mobile number With 10 Digits In Angular 2/4/5/8

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 
  1. <form #userForm="ngForm" (ngSubmit)="onFormSubmit(userForm)">  
  2.  <table>  
  3. <tr>  
  4.   <td>Mobile Number:</td>  
  5.   <td>  
  6.     <input name="mobileNumber" [ngModel]="user.mobileNumber" [pattern]="mobNumberPattern" #mobNumber="ngModel">  
  7.     <div *ngIf="mobNumber.errors && userForm.submitted && !isValidFormSubmitted" [ngClass] = "'error'">  
  8.       <div *ngIf="mobNumber.errors.pattern">  
  9.         Mobile number not valid.  
  10.       </div>   
  11.     </div>  
  12.   </td>  
  13.   </tr>    
  14.         
  15.   <tr>      
  16.   <td colspan="2">  
  17.     <button>Submit</button>  
  18.   </td>  
  19.   </tr>      
  20.  </table>   
  21. </form>  
app.component.ts
  1. import { Component } from '@angular/core';  
  2. import { NgForm } from '@angular/forms';  
  3.    
  4. @Component({  
  5.  selector: 'app-root',  
  6.  templateUrl: './app.component.html',  
  7.  styleUrls: ['./app.component.css']  
  8. })  
  9. export class AppComponent {  
  10.  title = 'FormValidation';  
  11.   mobNumberPattern = "^((\\+91-?)|0)?[0-9]{10}$";  
  12.  isValidFormSubmitted = false;  
  13.  user = new User();  
  14.    
  15.    
  16.  onFormSubmit(form: NgForm) {  
  17.    this.isValidFormSubmitted = false;  
  18.    if (form.invalid) {  
  19.       return;  
  20.    }  
  21.    this.isValidFormSubmitted = true;  
  22.    form.resetForm();  
  23. }  
  24. }  
  25.    
  26. export class User {  
  27.  mobileNumber ?: string;  
  28. }  
Output
 
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.
Next Recommended Reading Validate Email Id In Angular 2/4/5/8