[英]Adding custom validators to FormArray in Angular reactive forms
I have a reactive form like this 我有这样的反应形式
this.form = this.fb.group({
items: this.fb.array(
[
this.fb.group({
net_amount: [
null,
Validators.compose([
Validators.required,
Validators.pattern('^[0-9]+(.?[0-9]+)?$'),
isValidNumericValue
])
],
})
],
Validators.required
),
substances: this.initAdditives(),
net_total: [
this.currentProduct.net_total || null,
[
Validators.required,
Validators.pattern('^[0-9]+(.?[0-9]+)?$'),
isValidNumericValue
]
]
});
isValidNumericValue is a custom validator that checks whether a number is greater than zero. isValidNumericValue是一个自定义验证器,它检查数字是否大于零。 The problem is the validator works outside FormArray but not inside. 问题是验证器在FormArray外部但不在内部。
export function isValidNumericValue(AC: AbstractControl) {
if (AC.value <= 0) {
return { numericError: true };
}
return null;
}
i think your problem is , since you want to apply the validator to the fb.group you should do like this: 我认为您的问题是,由于您要将验证器应用于fb.group,因此您应该这样做:
this.fb.group({
net_amount: [null, [Validators.required, Validators.pattern('^[0-9]+(.?[0-9]+)?$')]
],
}, { validator: isValidNumericValue })
I will post you here a form with both validation "Group" and "Single": 我将在此处向您发布一个同时包含验证“组”和“单一”的表单:
First you need to create validation rules: 首先,您需要创建验证规则:
function emailMatch(c: AbstractControl): {[key: string]: boolean} | null {
let email = c.get('email');
let confirmEmail = c.get('confirmEmail');
if (email.value === confirmEmail.value) {
return null;
}
return { 'match': true };
}
This validation i will use for a star rating in a product for example: 我将这种验证用于产品的星级评定,例如:
function MyRangeFunction (min: number, max: number): ValidatorFn {
return (c: AbstractControl): {[key: string]: boolean} | null => {
if (ifYouGotError) {
return { 'range': true };
};
return null;
};
}
Now my form is this: 现在我的表格是这样的:
this.myForm = this.fb.group({
emailGroup: this.fb.group({
email: ['', [Validators.required, Validators.pattern('[a-z0-9._%+-]+@[a-z0-9.-]+')]],
confirmEmail: ['', Validators.required],
}, {validator: emailMatch}),
rating: ['', MyRangeFunction (1, 5)],
});
I think here you have all covered about validation! 我认为这里已经涵盖了验证的全部内容!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.