Wilmer
Wilmer

Reputation: 73

I don't get the return of cross-validation to template-driven forms

I am trying to get true to return when the passwords aren't the same.

My component

this.restrict = new FormGroup({
  email: new FormControl(this.user.email),
  newPassword: new FormControl ('', [Validators.required, Validators.pattern('(?=\\D*\\d)(?=[^a-z]*[a-z])(?=[^A-Z]*[A-Z]).{6,30}')]),
  confirmPassword: new FormControl(null, [Validators.required, Validators.minLength(6)]),
}, {validators: this.pwdMatchValidator});

get newPassword() { return this.restrict.get('newPassword');}
get confirmPassword() { return this.restrict.get('confirmPassword');}

pwdMatchValidator(frm: FormGroup) {
  let pass = frm.get('newPassword').value;
  let confirmPass = frm.get('confirmPassword').value;
  console.log(pass);
  console.log(confirmPass);
  return pass === confirmPass ? null: { notSame: true};
}

In the template I have

<p-password formControlName="confirmPassword"></p-password>
<small class="p-error" *ngIf="confirmPassword.hasError('required')">No puede estar vacio</small>
<small class="p-error" *ngIf="confirmPassword.hasError('minlength')">Debe ser de hasta 6 caracteres.</small>
<small class="p-error" *ngIf="confirmPassword.hasError('notSame', 'passwords')">Las contraseñan son diferentes.</small>
<button pButton pRipple label="Save" icon="pi pi-check" class="p-button-text" [disabled]="!restrict.valid"></button>

Currently the answer I get is always false

The concole.log(pass); and console.log(confirmPass); do they work and the save button is still disabled because the field was not validated, then how can I get notSame? I tried:

{{ restrict.get('confirmPassword').errors?.notSame }}
{{ restrict.get('confirmPassword').errors }}
{{ confirmPassword.hasError('notSame') }}

In angular examples, they show a shape that in my case (angular 12) doesn't work

In the Angular documentation I can't find a satisfactory concept of how to handle returns, could you please explain?

Upvotes: 2

Views: 104

Answers (1)

AVJT82
AVJT82

Reputation: 73367

You validator is set on the FormGroup not the confirmPassword formcontrol, so the check you need to do is actually on the parentForm:

<small ngIf="restrict.hasError('notSame')">...</small>

STACKBLITZ

Upvotes: 1

Related Questions