Angular 2多个验证器 [英] Angular 2 Multiple validators

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

问题描述

在表单字段上可以有多个验证者吗?我尝试了此操作,但它导致了一些奇怪的错误(即使满足要求,该字段也永远无效)

Is it possible to have multiple validators on a form field? I tried this, but it resulted in some strange errors (field was never valid, even if requirements were met)

this.username = new Control('', Validators.minLength(5), Validators.required);

如何使用多个验证器?

推荐答案

您可以使用Validators.compose()

this.username = new Control('', 
    Validators.compose(
        [Validators.minLength(5), Validators.required]));

供异步验证者使用

this.username = new Control('', null,
    Validators.composeAsync(
        [someAsyncValidator, otherAsyncValidator]));

异步验证器存在未解决的问题,尤其是与异步验证器结合使用的同步验证器不起作用

There are open issues with async validators, especially sync validators combined with async validators don't work

  • https://github.com/angular/angular/issues/8923
  • https://github.com/angular/angular/issues/1068

要使同步验证器与异步验证器一起使用,请将同步验证器包装在promise中,然后将其组成为异步验证器,例如

To make sync validators work with async validators, wrap the sync validators in promises and compose them as async valdiators like

this.username = new Control('', null,
    Validators.composeAsync([
        (control:Control) => Promise.resolve(Validators.minLength(5)(control)), 
        (control:Control) => Promise.resolve(Validators.required(control)),
        someAsyncValidator, otherAsyncValidator
    ]));

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

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