Angular - Custom Matform Validator does not work

Asked

Viewed 34 times

-2

I have the following code in the constructor of my component:

this.form = new FormGroup({
  id_periodo_ini: new FormControl(undefined),
  id_periodo_fim: new FormControl(undefined)
}) 

In the ngAfterContentInit() i try to add a custom Validator:

ngAfterContentInit(): void {

    this.form.get('id_periodo_ini').setValidators([
      Validators.required,
      this.periodoService.comparaPeriodo(
        this.form.get('id_periodo_ini').value,
        this.form.get('id_periodo_fim').value
      )
    ])

    this.form.get('id_periodo_fim').setValidators([
      Validators.required,
      this.periodoService.comparaPeriodo(
        this.form.get('id_periodo_ini').value,
        this.form.get('id_periodo_fim').value
      )
    ])

}

In my periodService, the method code comparaPeriodo() is like this:

public comparaPeriodo(periodoInicial: Periodo, periodoFinal: Periodo): ValidatorFn {
  return (control: AbstractControl): ValidationErrors | null => {

    console.log(periodoFinal, periodoInicial)
    if (
      (periodoInicial && periodoFinal) &&
      (periodoInicial.dt_inicial && periodoFinal.dt_inicial)
    ) {
      console.log(periodoInicial, periodoFinal)

      if (periodoFinal.dt_inicial < periodoInicial.dt_inicial) {
        console.log("Invalido")
        return {
          periodoInvalido: "O período inicial deve ser anterior ao período final"
        }
      }

    }
    return null;

  }
}

Only when I change the value of the fields "id_periodo_ini" and "id_periodo_fim" is always null.

I already put a (selectionChange) in the mat-select and there it is taking the correct value, but when it calls the "comparaPeriodo()" always appears null.

What else do I have to do to put a custom Validator?

Thanks in advance.

1 answer

0

I suggest creating this Validator in formGroup instead of creating directly in formControls, and instead of passing the values to your Validator, pass formControls directly and extract their values.

Alternatively, your validators are running before receiving the value, so when creating formControl, do it as follows:

const control = new FormControl('', { updateOn: 'blur', validators: [seus_validators_aqui]});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.