【发布时间】: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