irkhaladkar
irkhaladkar

Reputation: 49

Validators.pattern is not showing the error for mobile number

component.html

<div class="form-group">
            <label>Enter mobile</label>
            <input type="text" class="form-control" formControlName="mobile" ><br>
        </div>
        <div *ngIf="userGroup.controls.mobile.invalid && (userGroup.controls.mobile.dirty || userGroup.controls.mobile.touched)">
            <div *ngIf="userGroup.controls.mobile.errors.required">
                Mobile number cannot be blank
            </div>
            <div *ngIf="userGroup.controls.mobile.errors.pattern">
                Mobile number should be 10 digits only
            </div>
        </div>

component.ts

userGroup:FormGroup;

ngOnInit() { this.userGroup = this.fb.group({

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

}

For the blank it is working perfectly but for pattern it is not showing any error

Upvotes: 0

Views: 991

Answers (3)

Gabriel
Gabriel

Reputation: 1

For more than 1 validator, you should use it inside an array as second parameter. otherwise it will return an error on console and wont work.

Upvotes: 0

aelagawy
aelagawy

Reputation: 577

component.ts

userGroup:FormGroup;

//simple getter to easily access control from template
get mobile() { return this.userGroup.get('mobile'); }

ngOnInit() { 
   this.userGroup = this.fb.group({
      //also validators should passed in one array as a second argument to this literal
      mobile:['', [Validators.required, Validators.pattern(/^[0-9]{10}$/)]]
});

component.html

<div class="form-group">
   <label>Enter mobile</label>
   <input type="text" class="form-control" formControlName="mobile"><br>
</div>
<div *ngIf="mobile.invalid && (mobile.dirty || mobile.touched)">
   <div *ngIf="mobile.errors.required">
      Mobile number cannot be blank
   </div>
   <div *ngIf="mobile.errors.pattern">
      Mobile number should be 10 digits only
   </div>
</div>

Upvotes: 0

Jinu Joseph
Jinu Joseph

Reputation: 36

Try like this:

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

Upvotes: 2

Related Questions