Json Angular 5动态表单中的自定义验证器
我正在Angular 5中从一个可配置的json创建一个动态表单。一切正常,但我无法为特定字段添加自定义验证器Json Angular 5动态表单中的自定义验证器,json,angular,validation,angular2-forms,Json,Angular,Validation,Angular2 Forms,我正在Angular 5中从一个可配置的json创建一个动态表单。一切正常,但我无法为特定字段添加自定义验证器 TypeError: v is not a function Json 用于创建动态表单控件的组件: } 主要组件文件: 从'@angular/core'导入{Component,OnInit,Input}; 从'@angular/forms'导入{FormGroup,AbstractControl,FormControl}; 函数rangeValidator(c:FormContr
TypeError: v is not a function
Json
用于创建动态表单控件的组件:
}
主要组件文件:
从'@angular/core'导入{Component,OnInit,Input};
从'@angular/forms'导入{FormGroup,AbstractControl,FormControl};
函数rangeValidator(c:FormControl){
如果(c.value!==未定义&(isNaN(c.value)| | c.value>1 | | c.value<10)){
返回{range:true};
}
返回null;
}
@组成部分({
选择器:“应用程序问题”,
templateUrl:“./dynamic form question.component.html”,
样式URL:['./动态表单问题.component.css']
})
导出类DynamicFormQuestionComponent实现OnInit{
@输入()问题;
@Input()表单:FormGroup;
get isValid(){返回this.form.controls[this.question.key].valid;}
构造函数(){}
恩戈尼尼特(){
log(“我的表单”,this.form.value)
}
}
有什么想法,请帮忙
if (question.custom || question.custom.length > 0) {
question.custom.forEach((va) => {
vals.push(va);
});
}
您希望添加自定义验证器,但实际上您只需将字符串“rangeValidator”添加到验证器数组中。所以,是的,v不是一个函数:)
您应该将范围验证器声明为海关验证器的静态功能,如下所示:
export class CustomValidators {
static rangeValidator(c: FormControl) {
if (c.value !== undefined && (isNaN(c.value) || c.value > 1 || c.value < 10)) {
return { range: true };
}
return null;
}
getValidators(question) {
....
if (question.custom || question.custom.length > 0) {
question.custom.forEach((va) => {
vals.push(CustomValidators[va]);
});
}
return vals;
}
见
注意:这个叉子只能解决当前的问题。您的全局示例表单验证仍然不起作用非常感谢。它起作用了。您知道其他验证为什么不起作用吗?您的范围验证混乱:c.value>1 | | c.value<10每个数字都与此匹配,因此它将始终返回错误。你的情况是什么?是的,我错加了。非常感谢你的支持
if (question.custom || question.custom.length > 0) {
question.custom.forEach((va) => {
vals.push(va);
});
}
export class CustomValidators {
static rangeValidator(c: FormControl) {
if (c.value !== undefined && (isNaN(c.value) || c.value > 1 || c.value < 10)) {
return { range: true };
}
return null;
}
getValidators(question) {
....
if (question.custom || question.custom.length > 0) {
question.custom.forEach((va) => {
vals.push(CustomValidators[va]);
});
}
return vals;
}