Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Custom Validators in angular reactive forms

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.

like image 335
chandradot99 Avatar asked Feb 09 '26 15:02

chandradot99


1 Answers

try this:

return this.fb.group({
  'id': [project.id, Validators.required],
  'type': ['reward', Validators.required],
  'rewardAmount': ['', Validators.compose(validateAmount(this.goalAmount, this.quantity))]
});
like image 83
sainu Avatar answered Feb 12 '26 14:02

sainu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!