1

In component I have created form using form builder: For contact Number feild I have added validation mobRegex and I want to show msg when pattern does not match.

Component snippet:

createForm(): void {
    this.contactUsForm = this.fb.group({
        'name': ['', Validators.required],
        'email': ['', Validators.compose([
            Validators.required,
          //  Validators.pattern(this.emailRegex)])],
            Validators.email])],
        'queryType': [null, Validators.required],
        // 'date': ['', Validators.compose([ValidationService.spaceValidator, Validators.required])],
        //'subject': ['', Validators.required],
        'subject': ['', Validators.compose([
          Validators.required,
          Validators.maxLength(100)])],
       // 'message': ['', Validators.required],
        'message': ['', Validators.compose([
          Validators.required,
          Validators.maxLength(1024)])],
        'contactNumber': ['', Validators.compose([
          Validators.required,
          Validators.pattern(this.mobRegx)])]
    });
//     if (this.queries.selected.type.toLowerCase() == 'schedule-a-call')
//         this.contactUsForm.addControl('timeSlot', new FormControl('timeSlot', Validators.required);
}

In html I have contact field and markup is as below:

<div class="form-group">

  <input
  type="text"
  class="form-control input-lg"
  id="contactNumberInput"
  placeholder="Contact Number"
  formControlName="contactNumber"
  [formControl]=" contactUsForm.controls['contactNumber']"
  [(ngModel)]="support.contactNumber"
  required>


<div *ngIf="contactUsForm.get('contactNumber').touched && 
contactUsForm.get('contactNumber').invalid">
<div *ngIf="contactUsForm.get('contactNumber').hasError('required')">
   Contact Number is requied
 </div>
<div *ngIf="contactUsForm.get('contactNumber').hasError(mobRegx)">
  Contact Number should be a valid phone number  // This part is not working
</div>

I want to show an error msg when mobRegx does not match.

mobRegx = /^(+\d{1,3}[- ]?)?\d{10}$/;

Also can some one refer me some good article I can find built in rules/patterns for angular reactive forms?

1

1 Answer 1

3

You Can find all the guidelines about the validations and usage of the reactive form from the following tutorial

https://angular.io/guide/reactive-forms

and for applying pattern you can use validators.pattern()

https://angular.io/api/forms/PatternValidator for ex-

Validators.pattern('^[a-zA-Z]+$');
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for help @komalpreet singh! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.