Angular 它起作用了,在别的地方是个错误。创建自定义验证器
我正在自定义我的表单并创建自己的验证器。但我做错了,因为它总是崩溃:Angular 它起作用了,在别的地方是个错误。创建自定义验证器,angular,angular-reactive-forms,angular-custom-validators,Angular,Angular Reactive Forms,Angular Custom Validators,我正在自定义我的表单并创建自己的验证器。但我做错了,因为它总是崩溃: **my-component.ts** export function ageRangeValidator(min: number, max: number): ValidatorFn { return (control: AbstractControl): { [key: string]: boolean } | null => { if (control.value !== undefined &
**my-component.ts**
export function ageRangeValidator(min: number, max: number): ValidatorFn {
return (control: AbstractControl): { [key: string]: boolean } | null => {
if (control.value !== undefined && (isNaN(control.value) || control.value < min || control.value > max)) {
return { 'ageRange': true };
}
return null;
};
}
@Component({
selector: 'my-component',
templateUrl: './my-component.html',
styleUrls: ['./my-component.scss']
})
export class MyComponent implements OnInit {
form: FormGroup;
constructor(private fb: FormBuilder) {
}
ngOnInit() {
this.form = this.fb.group({
name: ['', [Validators.required],
age: ['', [Validators.required, ageRangeValidator(20, 30)]]
}
}
当创建表单时,我发现它崩溃了
Error: formGroup expects a FormGroup instance. Please pass one in.
Example:
<div [formGroup]="myGroup">
<input formControlName="firstName">
</div>
In your class:
this.myGroup = new FormGroup({
fistName: new FormControl()
});
如果我删除表单定义中的验证器,它就会工作
我做错了什么?您的年龄是一个字符串,在验证器中您正在比较数字。请确保使用正确的类型。为什么不使用数字输入字段和max+min验证器?您在组件文件中为表单提供的名称与在模板中为formGroup传递的名称是否相同?能否与我们共享my-component.html??这个解决方案是有效的,它在代码的其他部分是一个错误。这只是一个例子,我的验证器比它更复杂,这就是为什么我不使用max和min
// in your form
age : ['', [Validators.required, this.ageRangeValidator, Validators.maxLength(100)]],
// function in same class
public ageRangeValidator(control: FormControl) {
const isValid = control.value > 30 && control.value < 30;
return isValid ? null : { ageRange: true };
}