3

I have defined a custom validator like below

import { Directive, forwardRef } from '@angular/core';
import { NG_VALIDATORS, FormControl } from '@angular/forms';

function validateRewardAmountFactory(goalAmount: number, quantity: number) {
  return (c: FormControl) => {
    const rewardAmount = c.value;
    const isValidAmount = rewardAmount * quantity < goalAmount ? true : false;
    return isValidAmount ? null : { validateAmount: true };
  };
}

@Directive({
  selector: '[validateAmount][ngControl][validateAmount][ngModel],[validateAmount][ngFormControl]',
  providers: [
    { provide: NG_VALIDATORS, useExisting: forwardRef(() => RewardAmountValidator), multi: true }
  ]
})
export class RewardAmountValidator {

  validator: Function;

  constructor(goalAmount: number, quantity: number) {
    this.validator = validateRewardAmountFactory(goalAmount, quantity);
  }

  validate(c: FormControl) {
    return this.validator(c);
  }
}

and then i have declared this directive in my module

@NgModule({
  declarations: [RewardAmountValidator, ...]
})

Now i want to use this custom validator in my reactive form and i am doing it like this

return this.fb.group({
  'id': [project.id, Validators.required],
  'type': ['reward', Validators.required],
  'rewardAmount': ['', validateAmount(this.goalAmount, this.quantity)]
});

}

but it is giving me the error Cannot find name 'validateAmount'

So what is the correct way to use the custom validator in my reactive forms.

chandradot99
  • 3,616
  • 6
  • 27
  • 45

1 Answers1

2

try this:

return this.fb.group({
  'id': [project.id, Validators.required],
  'type': ['reward', Validators.required],
  'rewardAmount': ['', Validators.compose(validateAmount(this.goalAmount, this.quantity))]
});
sainu
  • 2,686
  • 3
  • 22
  • 41