1

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your answer! But the global validation error is set on the form group itself... Is the error set when the type validator is called? Could you add some sample code for your approach? Thanks!
With FormGroup you can just use the same method myFormGroup.hasError('myError') . If your typeValidator returns requiredIf: true then it sets the error for the FormGroup. Here is an example stackblitz.com/edit/angular-w3wqeo

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.