我在表单构建器中声明了我的验证器:
import { CustomValidators } from '../../custom-form-validators';
export class SelectTicketsComponent implements OnInit {
maxNumber: number = 20;
this.myForm = this.fBuilder.group({
fixtureName: 'Name',
totalTicketsSelected: [this.calculateTotalTicketsSelectedPerMatch(10), Validators.compose([Validators.required,
CustomValidators.checkNumbers.bind(this.maxNumber)])]
});
}
但我很困惑如何得到" maxNumber"变量到验证器检查它?
import { FormControl, Validators } from '@angular/forms';
// create your class that extends the angular validator class
export class CustomValidators extends Validators {
// create a static method for your validation
checkNumbers(control: FormControl): any {
/* I want to compare control.value to maxNumber here */
}
}
答案 0 :(得分:0)
了解如何创建自定义验证程序的最佳方法是检查Google是如何做到这一点的。我们来看看official validators
如您所见,您需要返回一个函数:
static min(min: number): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
if (isEmptyInputValue(control.value) || isEmptyInputValue(min)) {
return null; // don't validate empty values to allow optional controls
}
const value = parseFloat(control.value);
// Controls with NaN values after parsing should be treated as not having a
// minimum, per the HTML forms spec: https://www.w3.org/TR/html5/forms.html#attr-input-min
return !isNaN(value) && value < min ? {'min': {'min': min, 'actual': control.value}} : null;
};
}
答案 1 :(得分:0)
尽管这是一个非常老的问题,但我必须在此处发布答案(希望它将对像我这样的人有所帮助...)
将参数传递给我发现的验证器的方法是使用“绑定”运算符:
function CheckIfExistValidator(control: AbstractControl) {
// "movies" is something we passing
if (this.movies && this.movies.find(({title}) => title === control.value)) {
return { isExist: true };
}
return null;
}
在组件代码中,您可以编写如下内容:
this.newMovie = this.formBuilder.group({
title: ['', [Validators.required, CheckIfExistValidator.bind(this)]],
})