gpt4 book ai didi

validation - Angular 2 : Conditional required validation

转载 作者:太空狗 更新时间:2023-10-29 17:08:14 28 4
gpt4 key购买 nike

我正在尝试在特定字段上创建有条件的必需验证。我尝试通过在我的函数中返回 Validators.required 来执行此操作,但这似乎不起作用。我该怎么做呢?这是我的代码:

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);

}
});
};
};

非常感谢任何帮助。

最佳答案

我遇到了类似的问题,但找不到答案。由于还没有人回答这个问题,我将提供一个示例来说明我是如何解决我的问题的,以及您如何使用相同的解决方案来解决您的问题。

示例:(仅当未设置电子邮件时才需要电话号码)

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,然后相应地向“_helbred”添加 required。

关于validation - Angular 2 : Conditional required validation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40886324/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com