'Can I specify some validator update on change and some update on blur?

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?



Solution 1:[1]

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>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1