Gopesh
Gopesh

Reputation: 3950

Custom validator in Angular 5 dynamic forms

I am creating a dynamic form from a configurable json in Angular 5. Everything is working fine,but i am not able to add a custom validator for a particular field.I am getting an error like

TypeError: v is not a function

Json

{
      "key": "age",
      "label": "Age",
      "required": false,
      "order": 4,
      "controlType": "textbox",
      "validations": ['required', 'minlength'],
      "custom":['rangeValidator'],//custom validator function name
      "type": "email"
    }

Component to make dynamic form controls:

toFormGroup(questions) {
    let group: any = {};
    questions.forEach(question => {
      group[question.key] = new FormControl(question.value || '', this.getValidators(question)
      );
    });
    return new FormGroup(group);
  }

  getValidators(question) {
    let vals = [];
    question.validations.forEach((v) => {
      if (v == 'required') {
        vals.push(Validators.required);
      }
      if (v == 'minlength') {
        vals.push(Validators.minLength(4))
      }
    });
    if (question.custom || question.custom.length > 0) {
      question.custom.forEach((va) => {
        vals.push(va);
      });
    }

return vals;

}

Main Component file:

    import { Component, OnInit, Input } from '@angular/core';
   import { FormGroup, AbstractControl ,FormControl} from '@angular/forms';
function rangeValidator(c: FormControl) {
    if (c.value !== undefined && (isNaN(c.value) || c.value > 1 || c.value < 10)) {
      return { range: true };
    }
    return null;
  }
@Component({
  selector: 'app-question',
  templateUrl: './dynamic-form-question.component.html',
  styleUrls: ['./dynamic-form-question.component.css']
})
export class DynamicFormQuestionComponent implements OnInit {
  @Input() question;
  @Input() form: FormGroup;
  get isValid() { return this.form.controls[this.question.key].valid; }

  constructor() { }

  ngOnInit() {
    console.log("My form", this.form.value)

  }


}

Stackblitz Url

Any ideas,Please help

Upvotes: 0

Views: 2709

Answers (1)

Pierre Mallet
Pierre Mallet

Reputation: 7221

there

  if (question.custom || question.custom.length > 0) {
      question.custom.forEach((va) => {
        vals.push(va);
      });
    }

you want to add your custom validators, but in fact you just add to the validators array the string "rangeValidator". So yes v is not a function :)

You should should declare you range validators as a static function of your customs validators like that :

export class CustomValidators {
    static rangeValidator(c: FormControl) {
    if (c.value !== undefined && (isNaN(c.value) || c.value > 1 || c.value < 10)) {
      return { range: true };
    }
    return null;
  }

then import it in and use it like that :

 getValidators(question) {
    ....

    if (question.custom || question.custom.length > 0) {
      question.custom.forEach((va) => {
        vals.push(CustomValidators[va]);
      });
    }

    return vals;
  }

see the forked stackblitz

NB : this fork only resolve the current matter. You global example form validation still doesnt work

Upvotes: 1

Related Questions