【发布时间】:2017-01-06 10:06:09
【问题描述】:
我已关注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) 像上面那样传递一个参数。结果:错误
还有什么我可以尝试的吗?
【问题讨论】:
标签: angular validation ionic-framework