I have created a simple form to which I would like to add a validator:
form;
constructor() {
this.form = new FormGroup({
'old-password' : new FormControl('', [Validators.required, Validators.minLength(4)], PasswordValidators.checkPassword),
'new-password' : new FormControl('', [Validators.required, Validators.minLength(4)]),
'confirm-password' : new FormControl('', [Validators.required, Validators.minLength(4)])
}, {
validator: PasswordValidators.passwordsShouldMatch
});
}
But in validator
section I get an error which says:
[ts]
Argument of type '{ validator: (control: AbstractControl) => { passwordsShouldMatch: boolean; }; }' is not assignable to parameter of type 'ValidatorFn'.
Object literal may only specify known properties, and 'validator' does not exist in type 'ValidatorFn'.
(property) validator: (control: AbstractControl) => {
passwordsShouldMatch: boolean;
}
When I change the construction of the form to FormBuilder
it starts to working - why's that?
According to the api documentation and example the constructor is just getting the validator function, not an object as FormBuilder
does.
So this should work:
constructor() {
this.form = new FormGroup({
'old-password' : new FormControl('', [Validators.required, Validators.minLength(4)], PasswordValidators.checkPassword),
'new-password' : new FormControl('', [Validators.required, Validators.minLength(4)]),
'confirm-password' : new FormControl('', [Validators.required, Validators.minLength(4)])
},
PasswordValidators.passwordsShouldMatch
);
}
I'm not sure about what the PasswordValidators
object that you're using looks like but I rearranged your code to give you an example of the correct syntax that you should use in order to achieve what you want:
export class ModelDrivenForm {
public form: FormGroup;
constructor() {
this.form = new FormGroup({
oldpassword: new FormControl('', [Validators.required, Validators.minLength(4), this.checkPassword]),
newpassword: new FormControl('', [Validators.required, Validators.minLength(4)]),
confirmpassword: new FormControl('', [Validators.required, Validators.minLength(4)])
},
this.passwordsShouldMatch
);
}
private checkPassword(control: FormControl) {
return control.value.toString().length >= 5 && control.value.toString().length <= 10
? null
: {'outOfRange': true};
}
private passwordsShouldMatch(fGroup: FormGroup) {
return fGroup.get('password').value === fGroup.get('passwordConfirm').value
? null : {'mismatch': true};
}
}
P.S: the checkPassword
controls if the number of characters of the password is between 5
and 10
chars in the given example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With