0

我正在自定义我的表单并创建自己的验证器。但我做错了,因为它总是崩溃:

**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()
});

如果我删除表单定义中的验证器,它就可以工作。

我在做什么错?

4

2 回答 2

1
// 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 };
  }
于 2019-09-18T08:54:17.313 回答
0

您的年龄是一个字符串,在您的验证器中您正在比较数字。请确保使用正确的类型。你为什么不使用数字输入字段和 max+min 验证器?

于 2019-09-18T08:58:03.597 回答