【问题标题】:Custom Validation with parameter带参数的自定义验证
【发布时间】:2016-08-10 19:56:11
【问题描述】:

我正在使用 Ionic 2 和 Angular 2 beta 11。

我有一个完美运行的自定义验证器。但是,我现在需要添加另一个自定义验证方法,但似乎无法弄清楚如何将参数传递给它。

如下所示,我有一个自定义验证函数:

ValidationService.userNameExists(control, this.employeeService)

“控件”不存在

如何将控件 (FormControl) 传递给 userNameExists 函数?或者,我需要传递字段值(用户名的值)。

谢谢

register.ts

constructor(private nav: NavController, private builder: FormBuilder, employeeService: EmployeeService) {
    this.employeeService = employeeService;

    this.registerForm = builder.group({
        'username': ['', [Validators.required, Validators.minLength(5), Validators.maxLength(55), ValidationService.userNameValidator, ValidationService.userNameExists(control, this.employeeService)]],
        'password1': ['', [Validators.required, Validators.minLength(5), Validators.maxLength(45), ValidationService.passwordValidator]],
        'password2': ['', [Validators.required, Validators.minLength(5), Validators.maxLength(45), ValidationService.passwordValidator]]
        }, { 'validator': ValidationService.matchPassword('password1', 'password2') }
    );
}

“控件”不存在

ValidationService.ts

public static userNameExists(control: FormControl, employeeService: EmployeeService): any {
    return (control: FormControl) => {
        let userNameInput = control.value;
console.log('userNameExists: '+control.value);            
        let promise: Promise<EmployeeModel> = employeeService.getEmployeByUserName(userNameInput);
        promise.then((employeeModel: EmployeeModel) => {
            if (employeeModel.userName === userNameInput) {
                return { userNameExists: true };
            } else {
                return null;
            }
        });
    }
}

【问题讨论】:

    标签: javascript angularjs validation angular ionic2


    【解决方案1】:

    请记住,当您实例化 FormControl/FormGroup 时,您是在传递验证函数,而不是调用它。更改您的用户名声明如下:

    'username': ['', 
      [Validators.required, 
       Validators.minLength(5),
       Validators.maxLength(55),
       ValidationService.userNameValidator,
       (control) => ValidationService.userNameExists(control, this.employeeService)]]
    

    【讨论】:

    • 谢谢哈利。我会试试看。
    • 嗨,Richard,如果您还不知道,您可以用勾号标记问题的正确答案。如果一个问题有多个答案,这也将帮助其他人识别正确的答案:)
    • @Richard 我同意 Will.Harris,它应该被标记为正确答案。你的问题是我一直在寻找的,这个答案立即解决了它。
    猜你喜欢
    • 1970-01-01
    • 2018-07-29
    • 2016-10-25
    • 2016-08-13
    • 2017-08-30
    • 2019-07-02
    • 1970-01-01
    • 2014-05-29
    • 2012-05-17
    相关资源
    最近更新 更多