[英]validate a form using other form values
I have a reactive form and I want to create a custom validator, based on the inputs should be incremental.我有一个反应形式,我想创建一个自定义验证器,基于输入应该是增量的。
Those are my html and validator这些是我的 html 和验证器
<form [formGroup]="form">
<input type="number" matInput formControlName="value0" placeholder="value0" />
<input type="number" matInput formControlName="value1" placeholder="value1" />
<input type="number" matInput formControlName="value2" placeholder="value2" />
</form>
export function valuesValidator(previous: number): ValidatorFn {
return (control: AbstractControl): { [key: string]: boolean } | null => {
if (previous > control.value) {
return { 'incrementalValue': true };
}
return null;
};
}
the problem is when I try to use the validator when starting the form, I'm trying to get at same time than create and it crashes:问题是当我在启动表单时尝试使用验证器时,我试图在创建的同时获取,但它崩溃了:
private initForm() {
this.form = this.formBuilder.group({
value0: [this.value0, Validators.required],
value1: [this.value2, valuesValidator(this.form.value.value0)],
value2: [this.value3, valuesValidator(this.form.value.value1)],
});
} }
How can I use my validator?如何使用我的验证器?
I'm trying to get at same time than create and it crashes:
我试图在创建的同时获得,但它崩溃了:
What does that mean?这意味着什么?
However, what you are looking for is a Cross-Form Validator.但是,您正在寻找的是跨表单验证器。 You can read about examples here:
您可以在此处阅读示例:
A crossform validator is a validator which does not receive a FormControl, but a FormGroup. crossform 验证器是一个不接收 FormControl 而是接收 FormGroup 的验证器。 You then extract your required values from that FormGroup and use them together.
然后从该 FormGroup 中提取所需的值并将它们一起使用。
When I understand you right, then you want to validate, that value1 < value2 < value 3. That could look like this:当我理解你的正确时,那么你想要验证 value1 < value2 < value 3。这可能看起来像这样:
this.form = this.formBuilder.group({
value0: [this.value0, Validators.mandatory],
value1: [this.value1, Validators.mandatory],
value2: [this.value2, Validators.mandatory],
}, { validator: IncrementalValuesValidator });
const IncrementalValuesValidator: ValidatorFn = (fg: FormGroup) => {
const v1= fg.get('value0').value;
const v2= fg.get('value1').value;
const v3= fg.get('value2').value;
return v1 < v2 && v1 < v3 && v2 < v3
? null
: { 'incrementalValue': true };
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.