【问题标题】:Custom validator in Angular 5 dynamic formsAngular 5 动态表单中的自定义验证器
【发布时间】:2018-05-28 10:54:18
【问题描述】:

我正在从 Angular 5 中的可配置 json 创建一个动态表单。一切正常,但我无法为特定字段添加自定义验证器。我收到类似

的错误
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"
    }

制作动态表单控件的组件:

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;

}

主组件文件:

    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

任何想法,请帮助

【问题讨论】:

    标签: json angular validation angular2-forms


    【解决方案1】:

    那里

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

    您想添加自定义验证器,但实际上您只需将字符串“rangeValidator”添加到验证器数组中。所以是的 v 不是一个函数:)

    您应该像这样将范围验证器声明为海关验证器的静态函数:

    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;
      }
    

    然后将其导入并像这样使用它:

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

    forked stackblitz

    注意:这个分叉只解决当前问题。你的全局示例表单验证仍然不起作用

    【讨论】:

    • 非常感谢。它奏效了。知道为什么其他验证不起作用吗?
    • 你的范围验证搞砸了:c.value > 1 || c.value
    • 是的,弄错了。非常感谢您的支持
    猜你喜欢
    • 2017-03-26
    • 1970-01-01
    • 2019-02-15
    • 2022-07-07
    • 2023-03-22
    • 1970-01-01
    • 2017-12-02
    • 1970-01-01
    • 2023-03-12
    相关资源
    最近更新 更多