Search code examples
angularvalidationangular-reactive-forms

How to write custom validation pattern for Phone number


I'm trying to write custom validation for phone Number(India) my problem is it should validate for both mobile number and landline number. I'm thankful if anyone gives me a solution for this my validation code

contact:['', [Validators.required,Validators.pattern("/^[0-9]{10,10}$/")]],

HTML Code:

<div *ngIf="(submitted||f.contact.touched) && f.contact.invalid" class="error-msg">
    <div *ngIf="f.contact.errors.required">contact  is required</div>
    <div *ngIf="f.contact.errors.pattern">Please enter 10 digit Number</div>
</div>

Solution

  • I would do like this:

    contact = new FormControl('', [Validators.required, Validators.pattern("^[0-9]{10,12}$")]);
    

    Regex: ^[0-9]{10,12}$

    Where,

    [0,9]   - Accept 0 to 9 numbers
    {10,12} - Range
    

    StackBlitz