2

I have this form and validation function in the .ts :


 ngOnInit(): void {
    this.form = this.formBuilder.group(
      {
        email: ['', [Validators.required, Validators.email]],
        password: [
          '',
          [
            Validators.required,
            Validators.minLength(6),
            Validators.maxLength(40),
            this.checkPasswords.bind(this)
          ]
        ], 
        rePass: ['', [Validators.required, this.checkPasswords.bind(this)]],
        roles: ['', [Validators.required]],
      },
    );
  }
 
  get f(): { [key: string]: AbstractControl } {
    return this.form.controls;  
  }
  checkPasswords(): ValidatorFn {  
    let pass = this.form?.value.password;
    let confirmPass =  this.form?.value.rePass;
    return (control: AbstractControl): ValidationErrors | null =>  {
      return( pass === confirmPass) ? null : {notSame: control.value};
    }
  }

And this is in my HTML:

 <mat-error *ngIf="f.rePass.errors?.notSame">Error</mat-error>

So the validation function is updating correctly but it is not firing a signal to the HTML template. What am I doing wrong?

1 Answer 1

1

A validator function should take an AbstractControl and return null or an object indicating the error. You are supplying a function that receives no arguments and returns a validator function.

You should use something like this:

checkPasswords(control: AbstractControl): ValidationErrors | null {  
  let pass = this.form?.value.password;
  let confirmPass =  this.form?.value.rePass;
  return (pass === confirmPass) ? null : { notSame: control.value };
}

Also, you shouldn't use bind when using it, but rather this:

rePass: ['', [Validators.required, c => this.checkPasswords(c)]],
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot! That clears out a lot of questions. I used your answer, but I needed to change this.form?.value.password to this.form?.controls.password.value , because otherwise it wasn't taking the first input.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.