0

I declare a formcontrol like this:

serial: [null, [binaryLengthValidator(10), Validators.required]]

I want my customer validator trigger on blur, and the required validator trigger on change. How can I do it?

Suspended
  • 169
  • 2
  • 11
  • Does this answer your question ? https://stackoverflow.com/a/41973780/6444705 – Emilien Mar 21 '22 at 08:38
  • @Emilien I don't want all validators update on blur, I want some udpate on blur, and some update on change in the same formcontrol – Suspended Mar 21 '22 at 08:42

1 Answers1

0

You can't control when those validators will update individually, But you can create a callback function and set the errors manually.

  serial = new FormControl('', Validators.required);

  onSerialInput() {
    this.serial.setErrors({
      ...this.serial.errors,
      notBanana: this.serial.value !== 'Banana',
    });
  }

  onSerialBlur() {
    this.serial.setErrors({
      ...this.serial.errors,
      maxLength: Validators.maxLength(10)(this.serial),
    });
  }
<input
  [formControl]="serial"
  (input)="onSerialInput()"
  (blur)="onSerialBlur()"
/>
<ng-container *ngIf="serial.errors">
  <p *ngIf="serial.errors['required']">Required</p>
  <p *ngIf="serial.errors['notBanana']">Not Banana</p>
  <p *ngIf="serial.errors['maxLength']">Too Long</p>
</ng-container>
Chris Hamilton
  • 9,252
  • 1
  • 9
  • 26