使用参数进行自定义验证

时间:2016-08-10 19:56:12

标签: javascript angularjs validation angular ionic2

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

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

如下所示,我有一个自定义验证功能:

ValidationService.userNameExists(control, this.employeeService)

'control'不存在

如何将控件(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') }
    );
}

'control'不存在

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;
            }
        });
    }
}

1 个答案:

答案 0 :(得分:4)

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

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