简体   繁体   English

Angular2异步表单验证器(返回承诺)

[英]Angular2 Async Form Validator (return Promise)

I'm trying to update the Angular2 Forms Validation example to handle an Async Validation response. 我正在尝试更新Angular2 Forms Validation示例以处理Async Validation响应。 This way I can hit an HTTP endpoint to validate a username. 这样,我可以命中HTTP端点来验证用户名。

Looking at their code they currently aren't currently using a Promise and it's working just fine: 查看他们的代码,他们当前未使用Promise,并且工作正常:

/** A hero's name can't match the given regular expression */ / **英雄的名字不能与给定的正则表达式匹配* /

export function forbiddenNameValidator(nameRe: RegExp): ValidatorFn {
  return (control: AbstractControl): {[key: string]: any} => {
    const name = control.value;
    const no = nameRe.test(name);
    return no ? {'forbiddenName': {name}} : null;
  };
}

I'm trying to update to return a Promise. 我正在尝试更新以返回一个Promise。 Something like: 就像是:

/** A hero's name can't match the given regular expression */
export function forbiddenNameValidator(nameRe: RegExp): ValidatorFn {
  return (control: AbstractControl) => {
    const name = control.value;


    return new Promise( resolve => {
               resolve({'forbiddenName': {name}});
        });

  };
}

However, the result I get doesn't display the error message, it's showing undefined. 但是,我得到的结果没有显示错误消息,而是显示未定义。

在此处输入图片说明

My thought is it has something to do with the way they are handling displaying the errors: 我认为这与他们处理显示错误的方式有关:

  onValueChanged(data?: any) {
    if (!this.heroForm) { return; }
    const form = this.heroForm;

    for (const field in this.formErrors) {
      // clear previous error message (if any)
      this.formErrors[field] = '';
      const control = form.get(field);

      if (control && control.dirty && !control.valid) {
        const messages = this.validationMessages[field];
        for (const key in control.errors) {
          this.formErrors[field] += messages[key] + ' ';
        }
      }
    }
  }

However I'm not sure of a better way of doing this. 但是,我不确定这样做的更好方法。

Angular2 example: https://angular.io/docs/ts/latest/cookbook/form-validation.html#!#live-example Angular2示例: https ://angular.io/docs/ts/latest/cookbook/form-validation.html#!#live-example

Link to my example attempting to return Promise: https://plnkr.co/edit/sDs9pNQ1Bs2knp6tasgI?p=preview 链接到我的尝试返回Promise的示例: https : //plnkr.co/edit/sDs9pNQ1Bs2knp6tasgI? p =preview

The problem is that you add the AsyncValidator to the SyncValidator Array. 问题是您将AsyncValidator添加到SyncValidator数组。 AsyncValidators are added in a separate array after the SyncValidators: 在SyncValidators之后,将AsyncValidators添加到单独的数组中:

this.heroForm = this.fb.group({
  'name': [this.hero.name, [
      Validators.required,
      Validators.minLength(4),
      Validators.maxLength(24)
    ], 
    [forbiddenNameValidator(/bob/i)] // << separate array
  ],
  'alterEgo': [this.hero.alterEgo],
  'power':    [this.hero.power, Validators.required]
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM