3

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?

2
  • in your example, what is this.secondFormGroup supposed to be? Commented Feb 10, 2018 at 9:56
  • @Jota.Toledo the whole form with all fields (including budget) Commented Feb 10, 2018 at 10:49

1 Answer 1

4

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)]],
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.