2
我已經定義了一個自定義的驗證像下面如何使用自定義驗證的角度反應形式
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);
}
}
,然後我有我的模塊中聲明該指令
@NgModule({
declarations: [RewardAmountValidator, ...]
})
現在我想用這個在我的反應形式自定義的驗證,我做這樣的
return this.fb.group({
'id': [project.id, Validators.required],
'type': ['reward', Validators.required],
'rewardAmount': ['', validateAmount(this.goalAmount, this.quantity)]
});
}
,但它給我的錯誤Cannot find name 'validateAmount'
那麼,什麼是使用自定義驗證我的反應形式的正確方法。
http://stackoverflow.com/questions/31788681/angular2-validator-which-relies-on-multiple-form-fields –