我正在尝试实施自定义验证规则,以验证是否选中了复选框。
但我收到错误
error_handler.js:46 EXCEPTION: _this.subscribe is not a function
当我尝试添加自定义验证器
时validator.ts
import {Control} from "angular/common";
interface ValidationResult {
[key: string]: any;
}
export class CustomValidators {
static validateChecked(c: Control): ValidationResult {
return (c.value);
}
}
Component.ts
import {Component} from '@angular/core';
import {FormBuilder, FormGroup, Validators, FormControl} from '@angular/forms';
import {CustomValidators} from './validators.ts'
@Component({
selector: 'wizard',
templateUrl: './template.html',
})
/**
* @todo - check how first select is automatically active
* @todo - export form presets to form class
*/
export class Wizard {
myForm: FormGroup;
privacy: boolean;
// Prefilling the FormBuilder
constructor(private horizonService: HorizonService, fb: FormBuilder) {
this.myForm = fb.group({
'privacy': ['', Validators.required, CustomValidators.validateChecked],
});
}
onSubmit(values: string): void {
console.log('you submitted value: ', values);
}
}
答案 0 :(得分:7)
如果您需要多个验证器,则应使用Validators.compose
。所以你的代码应该是这样的:
constructor(private horizonService: HorizonService, fb: FormBuilder) {
this.myForm = fb.group({
'privacy': ['', Validators.compose([Validators.required, CustomValidators.validateChecked])],
});
}
您可以阅读有关验证工具here的精彩文章。
答案 1 :(得分:3)
我认为如果你稍微更改一下FormGroup构造函数,通过传递new FormControl()
并将Validators添加到数组中,它可能会有效。
喜欢的东西:
export class Wizard {
myForm: FormGroup;
constructor(private horizonService: HorizonService) {
this.myForm = new FormGroup({
privacy: new FormControl('', [
Validators.required,
CustomValidators.validateChecked
])
});
}
}
我建议您在CUSTOM VALIDATORS IN ANGULAR 2上阅读这篇文章。
问候。
答案 2 :(得分:2)
问题仅在于它的验证中缺少[]。
正确的形式是:
'privacy': ['', [Validators.compose([Validators.required, CustomValidators.validateChecked])]],