0
votes

I am trying to validate an input that check if the article that i am registering exists or not... so... i have a method that check in my database, then i set in a variable a boolean value.

Then i pass this variable to the validator... but something is not working.

VALIDATION FUNCTION:

   validateRef(controlref: boolean): ValidatorFn {
    return () => {

        if ( controlref == true  ) {
            return { 'validref': true };
        } 

        if (controlref == false) {
          return { 'validref': false}
        }
    };

MY FORM:

  constructor( private fb: FormBuilder ) {

    this.createForm();

  }

  createForm() {
    this.dataForm = this.fb.group({
      ref: ['', [Validators.required, this.validateRef(this.controlref)]],
    })
  }
}

The variable that i am passing to the function, i've checked and is working... but the this.data.controls.ref.errors is always null.

HERE STACKBLITZ

can you guys guide me with this? thank you

1
can you add your code in stackblitz.com - Chellappan வ
i am still trying to fix it, and i have an update... if I initialize the variable that i pass to True, the form this.dataform.controls.ref.errors = true; so... i dont understand ^^ - Sergio Cano
@Chellappan let me do it - Sergio Cano
the stackblitz is showing properly - Chellappan வ

1 Answers

0
votes

HTML

DEMO

<form [formGroup]="dataForm">
    <input placeholder="Enter Something" formControlName="ref">
    <div *ngIf="dataForm.get('ref').hasError('invalidRef')">
        the data is not entered
    </div>
</form>

component:

  ngOnInit() {
    this.dataForm = this.fb.group({
      ref: ['', [Validators.required, CustomvalidatorService.validateRef]],
    })
  }

custom-validator.service.ts:

import { Injectable } from '@angular/core';
import { AbstractControl, FormControl } from '@angular/forms';


@Injectable()
export class CustomvalidatorService {

  constructor() { }

  static validateRef(control: FormControl) {
    if (!control.value) {
      return { 'invalidRef': true };
    } else {
      return null;
    }
  }

}