[英]How to Set Custom Validator on FormControl Angular
How to Set Custom Validation Angular as i am getting undefined of controls 当我无法定义控件时,如何设置自定义验证角度
FormControl.setValidators(this.validateCall);
validateCall(): ValidatorFn {
return (control: FormControl): ValidationErrors | null => { // not getting control value here
const val = control.value;
if(val == null || val == undefined) {
return {
atLeastOneRequired: {
valid: false
}
}
}
return null;
}
Reactive forms validation. 反应形式验证。 form-validation
形式验证
this.heroForm = new FormGroup({
'name': new FormControl(this.hero.name, [
Validators.required,
Validators.minLength(4),
forbiddenNameValidator(/bob/i) // <-- Here's how you pass in the custom validator.
]),
'alterEgo': new FormControl(this.hero.alterEgo),
'power': new FormControl(this.hero.power, Validators.required)
});
Your custom validator seems incorrect. 您的自定义验证程序似乎不正确。 You should remove
你应该删除
return (control: FormControl): ValidationErrors | null => {
Also no need for the nested object in the error. 也不需要在错误中嵌套对象。 So modify your validator to:
因此,将验证器修改为:
validateCall(ctrl: AbstractControl): ValidationErrors | null {
const val = ctrl.value;
if (!val || val === '') {
return {
atLeastOneRequired: true
}
}
return null;
}
The way you are setting the validator to the formcontrol is correct, since according to your comment i did it here for common understanding actually I am using this on formControl not on the class . 您将验证器设置为formcontrol的方式是正确的,因为根据您的评论, 我在这里这样做是为了达成共识,实际上我在formControl而不是在class上使用了它 。 In some cases you might also need to manually call
updateValueAndValidity
on the form control after setting the custom validator. 在某些情况下,设置自定义验证器后,您可能还需要在表单控件上手动调用
updateValueAndValidity
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.