I know there is a lot of topics about the same subject on the web but I can't manage to find the solution that works for me.
I have a form make with the formBuilder of angular, it's a profile form in which we can change the password, so we have three password input: the old one, the new one, and a confirmation for the new password.
Here is the form :
this.editProfileForm = this.formBuilder.group({
lastname: ['', Validators.required],
firstname: ['', Validators.required],
email: ['', [Validators.required, Validators.email]],
phone: [this.phone.replace(/\s/g, ''), [Validators.pattern('[0-9]{10}')]],
birthdate: ['', [Validators.required]],
password: [''],
new_password: [''],
new_password_confirm: [''],
});
this.editProfileForm.setValidators([this.ageValidator, this.samePasswordValidator, this.requiredPasswordValidator]);
What I try to do is to make the passwords fields required only if one of them is not empty. If the user start typing in one of the passwords fields then the three are required.
Here is what I try :
public requiredPasswordValidator(form: FormGroup): any {
if (form.controls.password.value || form.controls.new_password.value || form.controls.new_password_confirm.value) {
form.controls.password.setValidators([Validators.required]);
form.controls.new_password.setValidators([Validators.required, Validators.minLength(6)]);
form.controls.new_password_confirm.setValidators([Validators.required, Validators.minLength(6)]);
}
}
It seems works but not perfectly, the fields became required only if I start typing on it and erase, and this for each fields. For example if I type in password field, the new and new_confirm are not required, but if I type a random letter in the new pw input and remove it then the field is required.
I don't know if my explications are really clear, if you need more ask me.
Thanks.
Edit
I tried with Ankur Jain solution but still have the same problem :
Here is the function :
public formControlValueChanged(): void {
this.editProfileForm.get('password').valueChanges.subscribe(
(mode: string) => {
if (mode) {
this.f.new_password.setValidators([Validators.required]);
this.f.new_password_confirm.setValidators([Validators.required]);
}
});
}
(I use this.f
because with juste new_password & new_password confirm it throw an error, the this.f
is a function that return editProfileForm.controls
)
And I call it in ngOninit :
this.formControlValueChanged();
I also try to add this.editProfileForm.updateValueAndValidity();
to the function but this change nothing.