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.

1

1 Answer 1

2

try this:

return this.fb.group({
  'id': [project.id, Validators.required],
  'type': ['reward', Validators.required],
  'rewardAmount': ['', Validators.compose(validateAmount(this.goalAmount, this.quantity))]
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.