加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angular2中的简单自定义验证

发布时间:2020-12-17 18:00:34 所属栏目:安全 来源:网络整理
导读:我已经创建了这个验证功能: private customValidateField(c: FormControl): any { return c.value[0] === 'a' ? null : { notValid: true };} 所以,在我的反应形式上: constructor(private fb: FormBuilder){ this.form = this.fb.group({ field: ['',Vali
我已经创建了这个验证功能:

private customValidateField(c: FormControl): any {
    return c.value[0] === 'a' ? null : { notValid: true };
}

所以,在我的反应形式上:

constructor(private fb: FormBuilder)
{
  this.form = this.fb.group({
    field: ['',Validators.required,this.customValidateField],...
  }
}

当我在这个字段中写任何字符时,我收到此错误:

Error: Expected validator to return Promise or Observable.

有任何想法吗?

解决方法

“field”数组中的第三项是异步验证器(或它们的数组).因此,要指定多个同步验证器,您需要:

将它们作为数组传递

this.fb.group({
  'formControlName': [this.hero.name,[
      Validators.required,Validators.minLength(4)
  ]]
});

或者将它们组合起来(如Jordi所写)使用

Validators.compose(...)

FormBuilder API文档没有详细讨论参数,但由于它只是使用FormControl-s创建FormGroup的快捷方式,因此您可以查看FormControl构造函数:
https://angular.io/docs/ts/latest/api/forms/index/FormControl-class.html

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读