You are currently working with a temple driven form. If you want to add custom validators I would advice to switch to Reactive forms (even if you do not need custom validators I would use the Reactive forms approach and not the template driven one, it gives you more control).
But if you want to stay firm with the template driven forms, you can add custom validators with Angular directives.
First you need to make a validation factory function. This is a function that builds and return the validation function.
import { Directive, forwardRef } from '@angular/core';
import { NG_VALIDATORS, AbstractControl, ValidatorFn, Validator, FormControl } from '@angular/forms';
// validation function
function validatePasswordMatchFactory() : ValidatorFn {
return (c: AbstractControl) => {
let inputPassword = c.value;
//Do a check if password matches
if(passwordMatches) {
// No error
return null;
} else {
// Error
return {
passwordMatch: {
valid: false
}
};
}
}
}
@Directive({
selector: '[passwordMatch][ngModel]',
providers: [
{ provide: NG_VALIDATORS, useExisting: passwordMathcValidator , multi: true }
]
})
export class passwordMathcValidator implements Validator {
validator: ValidatorFn;
constructor() {
this.validator = validatePasswordMatchFactory();
}
validate(c: FormControl) {
return this.validator(c);
}
}
Now you can add the directive to your HTML.
<div class="form-group col-md-6">
<input
type="password"
class="form-control"
[(ngModel)]="model.currentPassword"
#currentPassword="ngModel"
id="currentPassword"
name="currentPassword"
>
<div *ngIf="currentPassword.errors.passwordMatch" class="invalid-feedback">
<div> Current Password does not match.</div>
</div>
</div>
If it does not have to be a form validation, but you just want to show the alert in the html. You can solve it a lot more simple. Just set a boolean in your TS file for example : passwordDoesNotMatch = false;
Then you change it if it matches and back to false after you submit.
The HTML would then look like this:
<div *ngIf="passwordDoesNotMatch " class="invalid-feedback">
<div> Current Password does not match.</div>
</div>
Hope this helps!