我已关注Josh Moroney's tutorial创建自定义验证程序。我让它工作,能够打电话
newForm.ts
new FormControl(question || '',
Validators.compose([AgeValidator.ageIsValid])
);
AgeValidator.ts
interface ValidationResult {
[key: string]: any;
}
export class AgeValidator {
static ageIsValid(control: AbstractControl): ValidationResult {
console.log('this is control', control);
console.log('this is control.value', control.value);
if (isNaN(control.value)) {
return {
notValid: true,
message: 'this is not a number'
};
}
if (control.value % 1 !== 0) {
return {
notValid: true,
message: 'cant be zero'
};
}
if (control.value < 18) {
return {
notValid: true,
message: 'cant be less than 18'
};
}
if (control.value > 120) {
return {
notValid: true,
message: 'Must be less than 120'
};
} else {
return null;
}
}
}
是否可以在.ageIsValid
方法中添加参数,以便我可以指定有效的年龄?例如,
new FormControl(question || '',
Validators.compose([AgeValidator.ageIsValid(18)])
);
我尝试过:
1)摆脱static
并像使用任何其他方法一样使用.ageIsValid。结果:TS错误
2)传递如上所述的论点。结果:错误
我还能尝试其他什么吗?
答案 0 :(得分:1)
您可以使用具有实例方法的类(而不是静态)
class AgeValidator {
constructor(private someParam) {}
ageIsValid(control: AbstractControl): ValidationResult {
// use someParam here
}
}
var ageValidator = new AgeValidator('foo')
new FormControl(question || '',
Validators.compose([ageIsValid.ageIsValid.bind(ageValidator)])
);
或返回函数的函数
static ageIsValid (someParam) {
return (control: AbstractControl): ValidationResult => {
// use someParam here
}
}
new FormControl(question || '',
Validators.compose([ageIsValid('foo')])
);