【问题标题】:Angular Custom Async Validator returning {__zone_symbol__state: null, __zone_symbol__value: Array(0)}Angular 自定义异步验证器返回 {__zone_symbol__state: null, __zone_symbol__value: Array(0)}
【发布时间】:2017-10-26 02:00:09
【问题描述】:

我正在尝试实现自定义验证器。非异步的 (cannotContainSpaces) 工作得很好。异步的(shouldBeUnique),是的,目前是微不足道的,据我所知,它应该返回承诺,验证器对象应该解决这个问题。它没有。 formControl username 上的错误集合在控制台中显示:

{__zone_symbol__state: null, __zone_symbol__value: Array(0)}

表单组件:

import { CustomValidators } from './custom.validators';
import { Component, Input } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';

@Component({
  selector: 'signup-form',
  templateUrl: './signup-form.component.html',
  styleUrls: ['./signup-form.component.css']
})
export class SignupFormComponent {

  form = new FormGroup({
    username: new FormControl('', [ 
       CustomValidators.cannotContainSpaces,
       CustomValidators.shouldBeUnique
      //  Validators.email, 
    ]),
    password: new FormControl('', Validators.required)
  })

  get username() {
    return this.form.get('username');
  }

  keyPressed(){
    console.log(this.username.errors)
  }

}

自定义验证器方法:

import { AbstractControl, ValidationErrors } from "@angular/forms";

export class CustomValidators {
    static cannotContainSpaces(control: AbstractControl) : ValidationErrors | null {
        if ((<string>control.value).indexOf(' ') >= 0)
            return { cannotContainSpaces: true};
        return null;
    }

    static shouldBeUnique(control: AbstractControl) : Promise<ValidationErrors | null> {
        return new Promise((resolve, reject) => {
            setTimeout(function() {
                if (control.value === 'treve')
                    resolve({shouldBeUnique: true});
                else resolve(null);
            }, 2000);
        });
    }
}

相关 HTML:

<form [formGroup]="form">
    <div class="form-group">
        <label for="username">Username</label>
        <input 
            (keyup) = "keyPressed()" (blur) = "keyPressed()"
            formControlName="username"
            id="username" 
            type="text" 
            class="form-control">
        <div *ngIf="username.touched && username.invalid" class="alert alert-danger">
            <div *ngIf="username.errors.cannotContainSpaces">Username must not contain spaces</div>
            <div *ngIf="username.errors.shouldBeUnique">Sorry, that username has been taken</div>
        </div>
    </div>

【问题讨论】:

    标签: angular asynchronous promise custom-validators


    【解决方案1】:

    将异步验证器设置为第三个参数:

    username: ['', [sync validators here], [async validators here]]
    

    所以更改以下内容:

    username: new FormControl('', 
      [ 
       CustomValidators.cannotContainSpaces,
       CustomValidators.shouldBeUnique
      ]),
    

    到:

    username: new FormControl('', 
       [CustomValidators.cannotContainSpaces],
       [CustomValidators.shouldBeUnique]
    ),
    

    演示:http://plnkr.co/edit/OceHbSl3atPHdcvNRQDs?p=preview

    【讨论】:

    • 我搜索了 2 天为什么我的 AsyncValidators 不能正常工作,我发现了这个!异步验证器需要作为单独的参数添加。谢谢!
    • @Catalin 很高兴听到这个答案对您有用! :) :)
    猜你喜欢
    • 2017-11-20
    • 2021-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-06
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多