I'm trying to write a custom validator in which I check whether the value typed in a field is higher/lower than the property of an external object. This is my code:
// defining the user property in the constructor
this.user = this.authGuard.currentUser();
// This is my FromGroup defined in my init function
this.firstFormGroup = this.formBuilder.group({
name: ['', Validators.required],
budget: ['', [Validators.required, Validators.min(10), this.validateBudget]],
start_date: ['', Validators.required],
end_date: ['', Validators.required]
});
Then my validator function would work like this:
validateBudget(c: FormControl) {
const credits = this.user.credits / 100;
let valid = false;
if (credits < this.secondFormGroup.getRawValue().budget) {
valid = false;
} else {
valid = true;
}
return {
validateBudget: {
valid: false
}
};
}
However the above is not working. I get the errors: Cannot read property user of undefined. Cannot read property get of undefined and a myriad of other errors. How could I go about writing this validator so I can check what the user is typing in the budget field against what the user (this.user) has on the credits property?
You pass in a function (validator) to be executed later, but when it's executed the context of this is lost. To keep this as in this component that holds the form, use either fat arrow function:
budget: ['', /* */, (c: FormControl) => this.validateBudget(c)]],
Or bind:
budget: ['', /* */, this.validateBudget.bind(this)]],
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