Javascript 预期验证器返回 Promise 或 Observable

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50548062/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:38:27  来源:igfitidea点击:

Expected validator to return Promise or Observable

javascriptangularangular5angular-formsangular-validation

提问by Renê Silva Lima

Im trying to do a custom validation on Angular 5 but I'm facing the following error

我正在尝试对 Angular 5 进行自定义验证,但我面临以下错误

Expected validator to return Promise or Observable

I just want to return an error to the form if the value doesnt match the required, heres my code:

如果值与所需的值不匹配,我只想向表单返回错误,这是我的代码:

This is the component where is my form

这是我的表单所在的组件

  constructor(fb: FormBuilder, private cadastroService:CadastroService) {
    this.signUp = fb.group({
      "name": ["", Validators.compose([Validators.required, Validators.minLength(2)])],
      "email": ["", Validators.compose([Validators.required, Validators.email])],
      "phone": ["", Validators.compose([Validators.required, Validators.minLength(5)])],
      "cpf": ["", Validators.required, ValidateCpf]
    })     
   }

This code is in the file with the validation I want to implement:

此代码位于带有我要实施的验证的文件中:

import { AbstractControl } from '@angular/forms';

export function ValidateCpf(control: AbstractControl){
    if (control.value == 13445) {
        return {errorCpf: true}
    }
    return null;
}

Can someone help me? Does that type of validation only work with observables or can I do i without being a promise or observable? thanks

有人能帮我吗?这种类型的验证是否只适用于 observables 或者我可以在没有承诺或 observable 的情况下进行吗?谢谢

回答by Vimalraj

It means that you have to add multiple validators in array

这意味着您必须在数组中添加多个验证器

. Example:

. 例子:

With Error

有错误

profileFormGroup = {
  budget: [null, Validators.required, Validators.min(1)]
};

Above one throws error that validator to return Promise or Observable

上面一个抛出错误,验证器返回 Promise 或 Observable

Fix:

使固定:

profileFormGroup = {
  budget: [null, [Validators.required, Validators.min(1)]]
};

Explanation:

解释:

In angular Reactive form validation done by using in-built validators which could given in array in 2nd postion, when multiple validators used.

在 Angular Reactive 表单验证中,通过使用内置验证器完成,当多个验证器使用.

FIELD_KEY: [INITIAL_VALUE, [LIST_OF_VALIDATORS]]

FIELD_KEY:[INITIAL_VALUE,[LIST_OF_VALIDATORS]]

回答by Deblaton Jean-Philippe

The following should work :

以下应该工作:

  "cpf": ["", [Validators.required, ValidateCpf]]

the arguments the form control expects are the following :

表单控件期望的参数如下:

constructor(formState: any = null, 
            validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null,
            asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null)

from https://angular.io/api/forms/FormControl

来自https://angular.io/api/forms/FormControl

回答by Kamlesh

Validators.compose() is redundant;

Validators.compose() 是多余的;

You can just pass an array. OP's problem is caused by failure to wrap the validators in [] to make them an array, hence the minLength() one is assumed to be async and the resulting error message.

你可以只传递一个数组。OP 的问题是由于未能将验证器包装在 [] 中以使其成为一个数组,因此 minLength() 一个被假定为异步的,并且由此产生的错误消息。

I hope, this solution will help you. Thanks.

我希望,这个解决方案会对你有所帮助。谢谢。

回答by K.L Sathish

error: userName:['',[Validators.required,Validators.minLength(3)],forbiddenNameValidator(/password/)],

错误:用户名:['',[Validators.required,Validators.minLength(3)],forbiddenNameValidator(/password/)],

ans: userName:['',[Validators.required,Validators.minLength(3),forbiddenNameValidator(/password/)]],

ans: userName:['',[Validators.required,Validators.minLength(3),forbiddenNameValidator(/password/)]],

validators use only second parameter in inside array. not for outside array

验证器仅使用内部数组中的第二个参数。不适用于外部阵列

回答by Abdus Salam Azad

If you add multiple validators, then you need to add another third bracket '[]' and inside that, you should put your validators. Like Below:

如果添加多个验证器,则需要添加另一个第三个括号“[]”,并且在其中放置验证器。如下图:

this.yourForm= this.formBuilder.group({
    amount: [null, [Validators.required, Validators.min(1)]],
});

回答by John

Not directly related to the OP's question, but I got the same error on a slightly different problem. I had an async validator, but I forgot to return an Observable (or Promise) from it.

与 OP 的问题没有直接关系,但我在一个稍微不同的问题上遇到了同样的错误。我有一个异步验证器,但我忘记从中返回一个 Observable(或 Promise)。

Here was my original async validator

这是我原来的异步验证器

public availableEmail(formControl: FormControl) {
   if(formControl && formControl.value){
     return this.http.get('')
   }
}

The thing is, what if the if-statement is false? We do not return anything, and we get a runtime error. I added the return type (making sure the IDE complains if we do not return the correct type), and then I return of(true)in the case the if-sentence failing.

问题是,如果 if 语句是假的怎么办?我们没有返回任何东西,我们得到一个运行时错误。我添加了返回类型(如果我们没有返回正确的类型,确保 IDE 会抱怨),然后of(true)在 if 语句失败的情况下返回。

Here is the updated async validator.

这是更新的异步验证器。

public availableEmail(formControl: FormControl): Observable<any> {
   if(formControl && formControl.value){
     return this.http.get('someUrl');
   }
   return of(true);
}

回答by Achraf Farouky

Error:"cpf": ["", Validators.required, ValidateCpf]

错误:"cpf": ["", Validators.required, ValidateCpf]

Fix:"cpf": ["", [Validators.required, ValidateCpf]]

使固定:"cpf": ["", [Validators.required, ValidateCpf]]

回答by Laszlo Sarvold

I think it is good to clarify in addition to the accepted answer that the error happens because when using reactive forms for creating a FormControl, after the initial_value the following arguments are, respectively, synchronous validators and async validators grouped in the form of an array each. E.g:

我认为除了已接受的答案之外,最好澄清错误发生的原因,因为在使用反应式形式创建 FormControl 时,在 initial_value 之后,以下参数分别是同步验证器和异步验证器,它们分别以数组的形式分组. 例如:

myFormGroup = this.fb.group({
    myControl: ['', [ mySyncValidators?], [ myAsyncValidators?] ]
})

If the control happens to have just one of either, Angular accepts it as a single element. E.g.:

如果控件碰巧只有其中之一,Angular 会将其作为单个元素接受。例如:

myFormGroup = this.fb.group({
    myControl: ['', mySyncValidator, myAsyncValidator ]
})

Therefore, when forgetting about the brackets for grouping them Angular assumes the second validator item is part of the Async validators and so we get the Expected validator to return Promise or Observable

因此,当忘记将它们分组的括号时,Angular 假设第二个验证器项是异步验证器的一部分,因此我们得到 Expected validator to return Promise or Observable