【问题标题】:How to write a custom validator the uses external data Angular 5如何编写使用外部数据Angular 5的自定义验证器
【发布时间】:2018-02-10 09:30:11
【问题描述】:

我正在尝试编写一个自定义验证器,用于检查字段中键入的值是否高于/低于外部对象的属性。这是我的代码:

// defining the user property in the constructor
this.user        = this.authGuard.currentUser();

// This is my FromGroup defined in my init function
this.firstFormGroup = this.formBuilder.group({
  name: ['', Validators.required],
  budget: ['', [Validators.required, Validators.min(10), this.validateBudget]],
  start_date: ['', Validators.required],
  end_date: ['', Validators.required]
});

然后我的验证器函数将像这样工作:

validateBudget(c: FormControl) {
const credits = this.user.credits / 100;
let valid = false;

if (credits <  this.secondFormGroup.getRawValue().budget) {
  valid = false;
} else {
  valid = true;
}

return {
  validateBudget: {
    valid: false
  }
};

}

但是上述方法不起作用。我收到错误:无法读取未定义的属性用户。无法读取未定义的属性获取和无数其他错误。我该如何编写这个验证器,以便检查用户在预算字段中输入的内容与用户 (this.user) 在 credits 属性上的内容?

【问题讨论】:

  • 在你的例子中,this.secondFormGroup 应该是什么?
  • @Jota.Toledo 包含所有字段(包括预算)的整个表单

标签: angular validation typescript


【解决方案1】:

您传入一个稍后执行的函数(验证器),但是当它执行时,this 的上下文丢失了。要将this 保留在包含表单的组件中,请使用任一粗箭头函数:

budget: ['', /* */, (c: FormControl) => this.validateBudget(c)]],

bind:

budget: ['', /* */, this.validateBudget.bind(this)]],

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 2019-01-07
    • 1970-01-01
    • 2018-05-28
    相关资源
    最近更新 更多