0
votes

I have defined my custom Passwords validator like so:

  confirmPassword(group: AbstractControl): ValidationErrors | null {
    console.log('Validator invoked')    

    if ( group.get('password_verify')?.pristine === false ||
         group.get('password_verify')?.touched === true ) {
      return group.get('password_verify')?.value !== group.get('password')?.value ? {
        passwords: "Passwords mismatch"
      } : null
    }
    return null
  }

And used it in a standart way for FormGroup:

  form: FormGroup = new FormGroup({
    phone: new FormControl('', Validators.required),
    email: new FormControl('', [Validators.required, Validators.email]),
    passwords: new FormGroup({
      password: new FormControl(''),
      password_verify: new FormControl('', this.myValidator)
    }, this.confirmPassword),
    first_name: new FormControl('', Validators.required),
    last_name: new FormControl('', Validators.required),
  });

Problem is that console.log only invoked after i type something to 'password_verify' input. While standart Validators.required, f.x., invokes even if you just focus/unfocus input, without inputting anything.

How do i make my custom validator behave in the same way ? You may notice this.myValidator another custom validator w/o implementation. I tried making factory function ValidatorFn that returns () => {} to validate input(thinking may be that's a correct way), but no luck - validator won't be called on touch event.

Angular v10

1
Why you are you grouping password under passwords those should be simple two password fields with custom validators. - Kamran Khatti
Can you create stackblitz? - Chellappan வ
@KamranKhatti because i need to use custom validator that checks both fields, that's wh i group them. i found this solution here on stack, it had like 300+ votes - Anton

1 Answers

-1
votes

Try Angular Custom Validators

form: FormGroup = new FormGroup({
  phone: new FormControl('', Validators.required),
  email: new FormControl('', [Validators.required, Validators.email]),
  password: new FormControl(''),
  password_verify: new FormControl('')
  first_name: new FormControl('', Validators.required),
  last_name: new FormControl('', Validators.required),
}, { validators: confirmPassword });


export const confirmPassword: ValidatorFn = (control: FormGroup): ValidationErrors | null => {
 const password = control.get('password').value;
 const confirmPassword = control.get('password_verify').value;

 return password === confirmPassword ? null : { password_mismatch: true }
}