Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a custom validator the uses external data Angular 5

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?

like image 696
WagnerMatosUK Avatar asked Feb 27 '26 01:02

WagnerMatosUK


1 Answers

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)]],
like image 100
Harry Ninh Avatar answered Mar 01 '26 16:03

Harry Ninh