首页 > 解决方案 > FormControl 验证器始终无效

问题描述

在我之前的问题之后,我正在尝试创建一个自定义验证器,允许用户在文本输入中仅键入特定值。

app.component.ts:

export class AppComponent implements OnInit {
  myForm: FormGroup;
  allowedValuesArray = ['Foo', 'Boo'];

  ngOnInit() {
    this.myForm = new FormGroup({
      'foo': new FormControl(null, [this.allowedValues.bind(this)])
    });        
  }

  allowedValues(control: FormControl): {[s: string]: boolean} {
    if (this.allowedValuesArray.indexOf(control.value)) {
      return {'notValidFoo': true};
    }        
    return {'notValidFoo': false};
  }
}

app.component.html:

<form [formGroup]="myForm">
  Foo: <input type="text" formControlName="foo">
  <span *ngIf="!myForm.get('foo').valid">Not valid foo</span>
</form>

问题是fooFormControl 总是假的(myForm.get('foo').valid总是假的)。

在此处输入图像描述

我的实施有什么问题?

标签: javascriptangularformgroups

解决方案


您只需要在验证正常时返回 null 。并像下面一样更改该方法

private allowedValues: ValidatorFn (control: FormControl) => {
    if (this.allowedValuesArray.indexOf(control.value) !== -1) {
        return {'notValidFoo': true};
    }
    return null;    
}

推荐阅读