FormControl验证器始终无效 [英] FormControl validator always invalid

查看:45
本文介绍了FormControl验证器始终无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我之前的

我的实现有什么问题?

解决方案

只要验证成功,您只需返回null.并像下面那样更改该方法

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

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?

解决方案

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;    
}

这篇关于FormControl验证器始终无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆