如何编写一个自定义验证器,使用外部数据 Angular 5

3

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

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

但是上述方法并不起作用。我收到了以下错误:无法读取未定义的用户属性。无法读取未定义的get属性以及其他一系列错误。我该如何编写此验证器,以便可以检查用户在预算字段中输入的内容与用户(this.user)在信用属性中所拥有的内容是否相符?


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

4

您需要传入一个函数(validator)以便稍后执行,但是在执行时this的上下文会丢失。为了保持this与持有表单的组件一致,可以使用箭头函数:

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

或者使用 bind:
budget: ['', /* */, this.validateBudget.bind(this)]],

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接