Angular Form 10 digit Mobile number validation using minLength and maxLength validators. The phone number field can contain only numbers and any other alphabets and special characters are blocked using key charCode event or directive.
Any special characters like space, comma, etc are not allowed.
We are not allowing plus (+) symbol because if a country is selected in say dropdown that country code should be added separately.
Copy paste is also not allowed.
MobileNumberComponent
import {Component} from '@angular/core';
import {FormBuilder, FormGroup, Validators}
from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class MobileNumberComponent {
title = 'Mobile Number Validation';
validationForm: FormGroup;
formSubmitted = false;
constructor(private formBuilder: FormBuilder) { }
ngOnInit() {
this.initForm();
}
initForm() {
this.validationForm = this.formBuilder.group({
mobileNumber: ['', [Validators.required,
Validators.minLength(10), Validators.maxLength(10)]]
});
}
get f() {
return this.validationForm.controls;
}
numberOnly(e: any) {
var regex = new RegExp("^[0-9]+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(str)) {
return true;
}
e.preventDefault();
return false;
}
onFormSubmit() {
this.formSubmitted = true;
if (this.validationForm.invalid) {
return;
}
}
resetForm() {
this.validationForm.controls['mobileNumber'].setValue('');
}
}
MobileNumberComponent HTML
<form [formGroup]="validationForm"
(ngSubmit)="onFormSubmit()">
<div class="title">
<strong>Angular Mobile Number Validation</strong>
</div>
<div class="form-group">
<label for="mobile">Mobile</label>
<div class="control">
<input type="text" name="mobile" class="form-control"
(keypress)="numberOnly($event)" required
formControlName="mobileNumber" placeholder="Mobile Number"
onpaste="return false;"
[ngClass]="{'is-invalid': f.mobileNumber.errors
&& (formSubmitted || f.mobileNumber.touched
|| f.mobileNumber.dirty),
'is-valid': validationForm.valid }">
<div
*ngIf="f.mobileNumber.errors
&& (formSubmitted || f.mobileNumber.touched)">
<div *ngIf="f.mobileNumber.errors?.required"
class="text-danger">Mobile number is required
</div>
<div
*ngIf="f.mobileNumber.errors.maxlength || f.mobileNumber.errors.minlength"
class="text-danger">Not a valid Mobile Number.</div>
</div>
</div>
</div>
<br>
<div class="footer">
<input class="btn btn-primary btn-lg mr-1" type="submit"
value="Submit"> <input class="btn btn-info btn-lg"
type="submit" value="Reset" (click)="resetForm()">
</div>
</form>
ngClass is an attribute directive used to dynamically set the CSS class to the input HTML element. If it is invalid it will change the input field border to red and turns into green when the form is valid.
Next, we are replacing the keypress event in the HTML input element with the directive.
The keypress event (keypress)="numberOnly($event)" can be replaced with a directive. Just create a allow numbers only directive and replace keypress with AllownumbersonlyDirective selector appAllownumbersonly
Here it is demonstrated with a sample code.
<input type="text" name="mobile"
class="form-control"
appAllownumbersonly required>
The advantage of this directive is that we can reuse it in any component within the application.