Thierry Templier
Thierry Templier

Reputation: 202176

Display errors on fields with global validation

I want to implement a global validation on a form and change the color of some inputs according to this validation.

I have three fields. Two fields are required only if the value of the first field is 'test'.

Here is what I implemented:

function typeValidator(form: FormGroup) {
  const type = form.controls['field1'].value;
  if (type === 'test') {
    const field2 = form.controls['field2'].value;
    const field3 = form.controls['field3'].value;
    return (!field2 || !field3) ? { requiredIf: true } : null;
  }

  return null;
}

Regarding the HTML:

<mat-form-field color="accent">
  <mat-select formControlName="field1" placeholder="Field1">
    <mat-option value="test">Test</mat-option>
    <mat-option value="other">Other</mat-option>
  </mat-select>
</mat-form-field>

<mat-form-field color="accent">
  <mat-select formControlName="field2" placeholder="Field2">
    <mat-option *ngFor="let element of elements" [value]="element.id">{{element.name}}</mat-option>
  </mat-select>
</mat-form-field>

Validation works fine but I wanted to change the color to orange for field2 when I have a validation error of type requiredIf for the form.

Thanks for your help. Thierry

Upvotes: 1

Views: 573

Answers (1)

DevEng
DevEng

Reputation: 1194

Add typeValidator as a custom validator to the fields you want. You can check if a form control have a custom error by myFormControl.hasError('myError') That conditional can be used in class statements to add / remove a class based on the error state.

Upvotes: 1

Related Questions