Reputation: 2535
I have 2 fields, password and confirm password. So, how do i validate both? HTML:
<div class="mb-4 col-lg-6">
<label >Password
<span class="required">*</span>
</label>
<input class="form-control" type="password" placeholder="Password"
formControlName="Password">
<control-messages [control]="controls.Password" class="errorMessage"></control-messages>
<div class="errorMessage" *ngIf="validationPassBlank==1">{{errorMessage}}</div>
<div class='required' *ngIf="validationError == 1">{{errorMessage}}</div>
</div>
Upvotes: 1
Views: 9603
Reputation: 18647
You seems to be using Reactive Forms
You need to Create one more field
for Confirm Password
, and give different name as ConfirmPassword
In the FormGroup
declare one more field as "ConfirmPassword" and give.
ConfirmPassword: [''] ,{ validator: [ValidationService.matchingConfirmPasswords] }
Add function to check passwords,
static matchingConfirmPasswords(passwordKey: any) {
let passwordInput = passwordKey['value'];
if (passwordInput.Password === passwordInput.ConfirmPassword) {
return null;
}
else {
return passwordKey.controls['ConfirmPassword'].setErrors({ passwordNotEquivalent: true });
}
}
In your html:
<div class="mb-4 col-lg-6">
<label > Confirm Password
<span class="required">*</span>
</label>
<input class="form-control" type="password" placeholder=" Confirm Password"
formControlName="Password">
<control-messages [control]="registerForm.controls.ConfirmPassword" class="errorMessage"></control-messages>
</div>
Upvotes: 1
Reputation: 6983
Do something like this.
private buildForm(): void {
this.form = this.fb.group({
password: [null, Validators.required],
repeat: [null, Validators.required]
}, {validator: this.checkIfMatchingPasswords('password', 'repeat')});
}
private checkIfMatchingPasswords(passwordKey: string, passwordConfirmationKey: string) {
return (group: FormGroup) => {
const passwordInput = group.controls[passwordKey],
passwordConfirmationInput = group.controls[passwordConfirmationKey];
if (passwordInput.value !== passwordConfirmationInput.value) {
return passwordConfirmationInput.setErrors({notEquivalent: true});
} else {
return passwordConfirmationInput.setErrors(null);
}
};
}
And in the template inside the form.
<p *ngIf="form.get('repeat')?.errors?.notEquivalent">Passwords did not match</p>
<p *ngIf="form.get('repeat')?.errors?.required">Confirm password is required</p>
Upvotes: 5