FormControl validator always invalid

≡放荡痞女 提交于 2021-02-10 18:43:53

问题


Following my previous question, I'm trying to create a custom validator that allow the users to type only specific values in an input of text.

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>

The problem is that the foo FormControl is always false, (the myForm.get('foo').valid is always false).

What wrong with my implementation?


回答1:


you just need to return null when validation is ok. and change that method like below

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


来源:https://stackoverflow.com/questions/60818785/formcontrol-validator-always-invalid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!