Created
June 3, 2021 23:32
-
-
Save krrskl/d65933c249217d1a91b20a79665faeea to your computer and use it in GitHub Desktop.
Custom validator to password and password confirm using reactive forms
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/utils/custom-validators.ts | |
export const confirmPasswords = (control: AbstractControl) => { | |
if (control.get('password').value !== control.get('confirmPassword').value) { | |
control.get('confirmPassword').setErrors({ passError: true }); | |
return { passError: true }; | |
} | |
return null; | |
}; | |
component.ts | |
this.form = this.formBuilder.group( | |
{ | |
password: password(), | |
confirmPassword: password(), | |
}, | |
{ | |
validators: confirmPasswords, | |
}, | |
); | |
component.html | |
Dentro de tu form group agregas allí tus inputs de contraseña algo así: | |
<mat-form-field class="w-100"> | |
<mat-label>Contraseña</mat-label> | |
<input matInput autocomplete="new-password" formControlName="password" type="password" placeholder="Contraseña"/> | |
<mat-error *ngIf="form.get('password').invalid"> | |
<mat-error *ngFor="let validation of validationsMessage.password"> | |
<mat-error class="error-message" *ngIf="form.get('password').hasError(validation.type) && (form.get('password').dirty || form.get('password').touched)"> | |
{{ validation.message }} | |
</mat-error> | |
</mat-error> | |
</mat-error> | |
</mat-form-field> | |
<mat-form-field class="w-100"> | |
<mat-label>Confirmar contraseña</mat-label> | |
<input matInput autocomplete="new-password" type="password" formControlName="confirmPassword" placeholder="Confirmar Contraseña"/> | |
<mat-error *ngIf="form.get('confirmPassword').invalid"> | |
<mat-error *ngIf="form.get('confirmPassword').hasError('passError')"> | |
Las contraseñas introducidas no coinciden | |
</mat-error> | |
</mat-error> | |
</mat-form-field> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment