【问题标题】:Angular2: Unable to create custom validator classAngular2:无法创建自定义验证器类
【发布时间】:2017-03-03 03:40:26
【问题描述】:

这是使用标准 Angular 2 表单生成器创建的注册表单:

this.form = this.formBuilder.group({
    login : [
        this.formValue.login,
        [
            Validators.required,
            Validators.minLength(loginLength.min),
            Validators.maxLength(loginLength.max),
            regexpValidator(loginPattern),
        ],
        //my custom validator class to check if login already exists
        LoginExistenceValidator,
    ],
    password : [
        this.formValue.password,
        [
            Validators.required,
            Validators.minLength(passwordLength.min),
            Validators.maxLength(passwordLength.max),
        ],
    ],
});

正如这里提到的 - http://blog.thoughtram.io/angular/2016/03/14/custom-validators-in-angular-2.html#custom-validators-with-dependencies

事实证明,验证器也可以是类,只要它 实现一个 validate(c: FormControl) 方法。

因此可以注入服务以从验证器访问远程数据。

所以我创建了这样的验证器:

import { Injectable, Inject, forwardRef } from '@angular/core';
import { Validator, FormControl }         from '@angular/forms';

import { UsersAdapter } from 'common/adapters/users';

@Injectable()
export class LoginExistenceValidator implements Validator {

    private adapter;

    constructor(@Inject(forwardRef(()=>UsersAdapter)) adapter) {
        debugger
    }

    validate(control: FormControl) {
        console.log("yep i'm called");
        return function(control: FormControl){

            //validation logic

            let validator = new Promise((resolve)=>{
                //mock random success/fail for a while
                setTimeout(()=>{
                    let random = Math.round(Math.random());
                    let value = random ? null : { reserved: true };
                    console.log(resolve);
                    resolve(value);
                },2000);

            });

            return validator;

        }
    }
}

UserAdapter 是 Angular Http 的包装器,用于检索数据。现在我没有使用它,每个验证调用都应该返回随机的成功/失败结果。

此代码在浏览器中引发此类错误:

EXCEPTION: Cannot read property 'subscribe' of undefined

发生错误是因为 Angular 实际上并没有调用 validate(),并且 FormControl 实例传递给构造函数而不是提供的 UserAdapter 服务。

当我尝试使用函数而不是类时,一切正常。 如何告诉 Angular 正确使用我的验证类?提前致谢。

【问题讨论】:

    标签: javascript validation angular typescript angular2-forms


    【解决方案1】:

    您引用的句子是关于使用选择器在元素上应用的验证器指令。

    如果你以反应形式使用它,你需要传递一个函数

    validate() 方法应返回 PromiseObservable 而不是返回 PromiseObservable 的函数。

    validate(control: FormControl) {
        console.log("yep i'm called");
            return = new Promise((resolve)=>{
                //mock random success/fail for a while
                setTimeout(()=>{
                    let random = Math.round(Math.random());
                    let value = random ? null : { reserved: true };
                    console.log(resolve);
                    resolve(value);
                },2000);
    
            });
        }
    }
    

    然后像这样使用它

    this.form = this.formBuilder.group({
        login : [
            this.formValue.login,
            [
                Validators.required,
                Validators.minLength(loginLength.min),
                Validators.maxLength(loginLength.max),
                regexpValidator(loginPattern),
            ],
            //my custom validator class to check if login already exists
            new LoginExistenceValidator().validate,
        ],
        password : [
            this.formValue.password,
            [
                Validators.required,
                Validators.minLength(passwordLength.min),
                Validators.maxLength(passwordLength.max),
            ],
        ],
    });
    

    【讨论】:

    • 谢谢。现在它起作用了。我也明白,在我的情况下,Angular 不使用依赖注入,最好在构造函数中提供验证器作为服务。
    猜你喜欢
    • 2017-04-04
    • 1970-01-01
    • 2017-10-03
    • 1970-01-01
    • 2016-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-02
    相关资源
    最近更新 更多