angularangular-materialangular-reactive-formsangular-custom-validatorsmat-error

Mat error is not displaying error for custom validators but template is displaying error


app.component.html

    <div class="col-sm-3">
                            <mat-form-field class="col-sm-3" appearance="outline"
                                class="example-full-width input-small-size d-block">
                                <mat-label>Personal Phone 1
                                </mat-label>
                                <input matInput formControlName="phonePersonal01" type="number">
                                <mat-error *ngIf="personalform.errors?.invalidPhoneMatch">
                                    Enter different numbers.
                                </mat-error>
<!-- This error is not displaying -->
                            </mat-form-field>{{personalform.errors|json}} 
    <!-- Output is : { "invalidPhoneMatch": true }-->
                        </div>

app.component.ts

personalform = this.fb.group({

        
        
        phno: ['', [Validators.required, Validators.pattern('\\+{0,1}[0-9]{10,12}')]],
        phonePersonal01: ['', [Validators.required, Validators.pattern("\\+{0,1}[0-9]{10,12}")]],
        phonePersonal02: ['', [Validators.required, Validators.pattern("\\+{0,1}[0-9]{10,12}")]],
    
      }, { validator: this.checkContactNumbers }
      );

...

checkContactNumbers(c: FormBuilder) {
    //safety check
    console.log(c[`value`][`phno`]);
    console.log(c[`value`][`phonePersonal01`]);

    if (c[`value`][`phno`] == c[`value`][`phonePersonal01`])
    {
      console.log('this ran');
      
      return { invalidPhoneMatch: true }
    }
  
  }

I am trying a custom validator. the html form json pipe is showing the output but mat error is not displaying output.


Solution

  • As this is your own error you cannot access it as a property of the control. Do it this way instead:

    <mat-error *ngIf="personalform.hasError('invalidPhoneMatch')">
    

    Second. The way you build your error object is wrong either. You have to have this structure:

    return {invalidPhoneMatch: {value: true}};
    

    Second approach

    Make the validator a validator of the form field's controller.

    personalform = this.fb.group({
        phno: ['', [Validators.required, Validators.pattern('\\+{0,1}[0-9]{10,12}')]],
        phonePersonal01: ['', [Validators.required, this.checkContactNumbers, Validators.pattern("\\+{0,1}[0-9]{10,12}")]],
        phonePersonal02: ['', [Validators.required, Validators.pattern("\\+{0,1}[0-9]{10,12}")]],
    });