0

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

  • i think your console throw following error: expected validator to return promise or observable in angular. so please use following link to fix issue. https://stackoverflow.com/questions/50548062/expected-validator-to-return-promise-or-observable – Vignesh Mar 12 '20 at 06:49
  • i think @Jinu answer fix your issue.For more info check that link which i given. – Vignesh Mar 12 '20 at 06:52

3 Answers3

2

Try like this:

mobile:['',[Validators.required,Validators.pattern(/^[0-9]{10}$/)]]
});
4b0
  • 21,981
  • 30
  • 95
  • 142
0

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>
aelagawy
  • 557
  • 5
  • 16
0

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.

  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-ask). – Community Sep 16 '21 at 17:08