FormControl验证器始终无效

时间:2020-03-23 17:37:02

标签: javascript angular formgroups

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

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>

问题在于foo FormControl始终为false,(myForm.get('foo').valid始终为false)。

enter image description here

我的实现有什么问题?

1 个答案:

答案 0 :(得分:3)

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

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