[英]How to implement validation in CVA?
I create form, one of field of this form is a cantrolValueAcessor-component.我创建表单,此表单的字段之一是 cantrolValueAcessor 组件。 This field is just a number and couple buttons.
该字段只是一个数字和几个按钮。 After clicking on left button number decrease, after clicking on right button number is increase.
点击左键后数字减少,点击右键后数字增加。
I want to use validation for cantrolValueAcessor-field.我想对 cantrolValueAcessor 字段使用验证。 The error message must to displays when number is less than '0'.
当数字小于“0”时,必须显示错误消息。
CVA code: CVA代码:
import { Component, forwardRef } from '@angular/core';
import {
ControlValueAccessor,
NG_VALIDATORS,
NG_VALUE_ACCESSOR,
Validator,
} from '@angular/forms';
@Component({
selector: 'hello',
template: `
<button (click)="minus()">minus</button>
<button (click)="plus()">plus</button>
{{ value }}
`,
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => HelloComponent),
multi: true,
},
{
provide: NG_VALIDATORS,
useExisting: forwardRef(() => HelloComponent),
multi: true,
},
],
})
export class HelloComponent implements ControlValueAccessor, Validator {
value: number;
validate() {
return this.value > 0 ? null : { positive: true };
}
onChange: any = () => {};
onTouch: any = () => {};
registerOnChange(fn: any) {
this.onChange = fn;
}
registerOnTouched(fn: any) {
this.onTouch = fn;
}
writeValue(input: number) {
this.value = input;
}
minus() {
this.value -= 1;
}
plus() {
this.value += 1;
}
}
parent code:父代码:
this.form = this.fb.group({
name: [null, [Validators.required]],
email: [null, [Validators.required, Validators.email]],
buttons: [0],
});
Since you're already using a form control, you can easily add them minValue
validator, then check for that error in the form control object.由于您已经在使用表单控件,因此您可以轻松地添加它们
minValue
验证器,然后在表单控件 object 中检查该错误。
https://angular.io/api/forms/Validators#min https://angular.io/api/forms/Validators#min
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.