【问题标题】:Custom Validation expects promises自定义验证期望承诺
【发布时间】:2018-06-21 23:30:16
【问题描述】:

我正在派生一种用于验证范围的自定义验证方法,如下所示:

static ratingRange=(min:number,max:number) =>
  {
     return (control:AbstractControl):Promise<ValidationErrors|null>=>
     {
          return new Promise(resolve=>
           {
             if (control.value !== undefined && (isNaN(control.value) 
            || control.value < min || control.value > max))
                              return resolve({InvalidRange:true});
             else return resolve(null);    
           }
          );
      }

它正在按预期执行验证,没有任何问题。

但是出于测试目的,我想使用ValidatorFn factory 重写验证方法,如下所示。(意图不是返回一个承诺对象)

static CustomRangeValidator (min:number,max:number): ValidatorFn
  {
     return (control:AbstractControl):{[key:string]:boolean}=>
     {
        if (control.value !== undefined && (isNaN(control.value) 
           || control.value < min || control.value > max))
                       return {InvalidRange:true}
        else return null;   
     }
  }

但我得到了

'期望验证器返回 Promise 或 Observable。'

有没有办法在不返回 Promise 对象的情况下重构我的函数调用?

【问题讨论】:

标签: angular custom-validators


【解决方案1】:

我的解决方案

this.myForm = new FormGroup({
    'controlName': new FormControl(value, 
               [/* this array for validation functions which will not return promises */], 
               [/*this array for function which returns promises*/])
})

/// in your case but your function in the first array 

【讨论】:

  • 你的意思是像 Valaidators.required 等默认验证器不需要 Promise 和自定义验证器需要 Promise 对象吗?
  • 不,我的意思是你可以自定义你的验证器,你可以指定是否需要承诺,如果需要承诺,把它放在第二个数组中,否则放在第一个数组中
  • 区别在于异步验证与同步验证:stackoverflow.com/questions/41434362/…
猜你喜欢
  • 2015-05-21
  • 2017-04-06
  • 2019-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-20
相关资源
最近更新 更多