问题描述
我正在尝试在特定字段上创建条件要求验证.我尝试通过在我的函数中返回 Validators.required 来执行此操作,但这似乎不起作用.我该怎么做?这是我的代码:
I am trying to create a conditional required validation on a specific field.I try doing this by return Validators.required back in my function, but this doesn't seem to work. How do I go about doing this? Here's my code:
private _ansat: AbstractControl = new FormControl('', Validators.required);
private _helbred: AbstractControl = new FormControl('', Validators.compose([this.useValidateIfRadio(this._ansat, 0, Validators.required)]) );
constructor(private _fb: FormBuilder) {
this.myForm = this._fb.group({
ansat: this._ansat,
helbred: this._helbred
});
}
useValidateIfRadio (c: AbstractControl, n: number, v) {
return function (control) {
return new Promise(resolve => {
// this.msg = ansatControl.value;
console.log(v);
if (c.value === n) {
resolve(v);
}
else {
resolve(null);
}
});
};
};
非常感谢任何帮助.
推荐答案
我遇到了类似的问题,但找不到答案.由于还没有人回答这个问题,我将举例说明我如何解决我的问题,以及如何使用相同的解决方案解决您的问题.
I had a similar problem but couldn't find a answer. Since nobody has answered this yet I'll provide an example of how I solved my problem, and how you can solve your issue using the same solution.
示例:(仅当未设置电子邮件时才需要电话号码)
Example: (Phone number is required only if email is not set)
export class UserComponent implements OnInit {
userForm: FormGroup;
constructor(private fb: FormBuilder) {}
ngOnInit() {
//Create my userForm and and add initial validators
this.userForm = this.fb.group({
username: [null, [Validators.required]],
name: [null, [Validators.required]],
email: [],
phoneNumber: [null, [Validators.required, Validators.minLength(4)],
});
//Listen to email value and update validators of phoneNumber accordingly
this.userForm.get('email').valueChanges.subscribe(data => this.onEmailValueChanged(data));
}
onEmailValueChanged(value: any){
let phoneNumberControl = this.userForm.get('phoneNumber');
// Using setValidators to add and remove validators. No better support for adding and removing validators to controller atm.
// See issue: https://github.com/angular/angular/issues/10567
if(!value){
phoneNumberControl.setValidators([Validators.required, Validators.minLength(4)]);
}else {
phoneNumberControl.setValidators([Validators.minLength(4)]);
}
phoneNumberControl.updateValueAndValidity(); //Need to call this to trigger a update
}
}
因此,在您的情况下,您应该向_ansat"添加一个等于我的电子邮件侦听器的 changeListener,然后相应地将 required 添加到_helbred".
So in your case you should add a changeListener to "_ansat" equal to my email listener, and then add required to "_helbred" accordingly.
这篇关于Angular2:条件要求的验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!