Home > Software engineering >  How to implement validation in CVA?
How to implement validation in CVA?

Time:03-15

I create form, one of field of this form is a cantrolValueAcessor-component. This field is just a number and couple buttons. After clicking on left button number decrease, after clicking on right button number is increase.

I want to use validation for cantrolValueAcessor-field. The error message must to displays when number is less than '0'.

Here is my attempt.

CVA code:

import { Component, forwardRef } from '@angular/core';
import {
  ControlValueAccessor,
  NG_VALIDATORS,
  NG_VALUE_ACCESSOR,
  Validator,
} from '@angular/forms';

@Component({
  selector: 'hello',
  template: `
    <button (click)="minus()">minus</button>
    <button (click)="plus()">plus</button>
    {{ value }}
  `,
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => HelloComponent),
      multi: true,
    },
    {
      provide: NG_VALIDATORS,
      useExisting: forwardRef(() => HelloComponent),
      multi: true,
    },
  ],
})
export class HelloComponent implements ControlValueAccessor, Validator {
  value: number;

  validate() {
    return this.value > 0 ? null : { positive: true };
  }

  onChange: any = () => {};
  onTouch: any = () => {};

  registerOnChange(fn: any) {
    this.onChange = fn;
  }
  registerOnTouched(fn: any) {
    this.onTouch = fn;
  }

  writeValue(input: number) {
    this.value = input;
  }

  minus() {
    this.value -= 1;
  }

  plus() {
    this.value  = 1;
  }
}

parent code:

this.form = this.fb.group({
      name: [null, [Validators.required]],
      email: [null, [Validators.required, Validators.email]],
      buttons: [0],
    });

CodePudding user response:

Since you're already using a form control, you can easily add them minValue validator, then check for that error in the form control object.

https://angular.io/api/forms/Validators#min

  • Related