问题
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