Custom Validation: Password Confirmation
Mustafa is right that you're better off using reactive forms when you are using Angular Material and the mat-error tags. However, here is a more complete version including all the validation messages, since you asked for 'A LOT OF' help.
I improved the Mustafa's validator a little too. This will help you get rid of all weirdness with the validation messages.
The visibility icon logic was removed since material password inputs already have this functionality built in.
Script:
form: FormGroup;
constructor(private fb: FormBuilder) {}
ngOnInit() {
this.form = this.fb.group(
{
password: [
'',
[
Validators.required,
Validators.minLength(8),
Validators.maxLength(100),
],
],
confirmPassword: [
'',
[
Validators.required,
Validators.minLength(8),
Validators.maxLength(100),
],
],
},
{ validator: CustomValidators.MatchingPasswords }
);
}
The improved custom validator:
export class CustomValidators {
static MatchingPasswords(control: AbstractControl) {
const password = control.get('password').value;
const confirmPassword = control.get('confirmPassword').value;
const currentErrors = control.get('confirmPassword').errors
const confirmControl = control.get('confirmPassword')
if (compare(password, confirmPassword)) {
confirmControl.setErrors({...currentErrors, not_matching: true});
} else {
confirmControl.setErrors(currentErrors)
}
}
}
function compare(password: string,confirmPassword: string) {
return password !== confirmPassword && confirmPassword !== ''
}
Template:
<form [formGroup]="form">
<mat-form-field>
<mat-label>Password</mat-label>
<input
matInput
type="password"
placeholder="Password"
formControlName="password"
/>
<mat-error *ngIf="form.get('password').hasError('required')">
Password is required!
</mat-error>
<mat-error *ngIf="form.get('password').hasError('minlength')">
Password should be longer than 8 characters!
</mat-error>
<mat-error *ngIf="form.get('password').hasError('maxlength')">
Password can't be longer than 100 characters!
</mat-error>
</mat-form-field>
<mat-form-field>
<mat-label>Confirm Password</mat-label>
<input
matInput
placeholder="Confirm your password..."
formControlName="confirmPassword"
type="password"
/>
<mat-error *ngIf="form.get('confirmPassword').hasError('required')">
Password confirmation is required!
</mat-error>
<mat-error *ngIf="form.get('confirmPassword').hasError('minlength')">
Password should be longer than 8 characters!
</mat-error>
<mat-error *ngIf="form.get('confirmPassword').hasError('maxlength')">
Password can't be longer than 100 characters!
</mat-error>
<mat-error *ngIf="form.get('confirmPassword').hasError('not_matching')">
The password doesn't match!
</mat-error>
</mat-form-field>
</form>
You can clean up all the mat-error tags, by providing the message with a function.
Here's an example on Stackblitz for you to play with.