1
votes

I am using Ionic 2 with Angular 2 beta 11.

I have a custom validator that works perfectly. However, I now need to add another custom validation method, but can't seem to work out how to pass a parameter to it.

As you can see below, I have a custom validation function:

ValidationService.userNameExists(control, this.employeeService)

'control' does not exist

How do I pass the control (FormControl) to the userNameExists function? Or, I need to pass the field value (value of username).

Thanks

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' does not exist

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

1 Answers

4
votes

Remember that when you are instantiating FormControl/FormGroup, you are passing the validation function in, not calling it. Change your username declaration as following:

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