Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Custom validator to password and password confirm using reactive forms
/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