Angular Mobile Number Validation with Bootstrap
Mobile number validation is a common task in web development, especially in forms where users are required to enter their phone numbers. In this article, we will demonstrate how to implement mobile number validation in an Angular project using Bootstrap.
Step 1: Create an Angular project
First, make sure you have Angular CLI installed on your machine. If not, you can install it by running the following command:
npm install -g @angular/cli
Next, create a new Angular project by running the following command:
ng new mobile-number-validation
Step 2: Create a form with mobile number input
In your Angular project, create a new component for the form by running the following command:
ng generate component mobile-number-form
Now, open the template file mobile-number-form.component.html
and add the following code:
<form class="form">
<div class="form-group">
<label for="mobileNumber">Mobile Number</label>
<input type="tel" class="form-control" id="mobileNumber" name="mobileNumber" placeholder="Enter mobile number" required>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
Step 3: Add mobile number validation
To add mobile number validation, open the TypeScript file mobile-number-form.component.ts
and add the following code:
import { Component } from '@angular/core';
import { FormControl, Validators } from '@angular/forms';
@Component({
selector: 'app-mobile-number-form',
templateUrl: './mobile-number-form.component.html',
styleUrls: ['./mobile-number-form.component.css']
})
export class MobileNumberFormComponent {
mobileNumber = new FormControl('', [Validators.required, Validators.pattern('[0-9]{10}')]);
}
Step 4: Test the mobile number validation
Now, run your Angular project by using the following command:
ng serve
Open your browser and navigate to http://localhost:4200
. Try entering a mobile number with less than or more than 10 digits and see the validation in action!
That’s it! You have successfully implemented mobile number validation in an Angular project using Bootstrap. Feel free to customize the validation rules and styles to suit your needs.