我正在基于条件验证对表单进行验证。条件验证是,当用户单击性别值“是”时,我需要在此之后显示hardFormSection,然后我需要对两个部分都进行验证,如果值是“否”,则隐藏该部分并清除该隐藏部分的验证。
我所做的是我创建了两种形式,并在订阅更改事件上进行了验证。但是我得到的问题是,如果我使一种形式无效,那么错误消息就会到来,但是在那之后我转到其他形式的值时,我已经使之无效的形式的验证消息就消失了,并允许保存数据和反之亦然。
在此先感谢您提供解决方案,如果有人有其他逻辑要做此验证,则也建议这样做。请验证HTml结构。
我正在共享我的代码#1).ts文件
ngOninit{
this.eForm = this.formBuilder.group({
id: [this.evaluationObject.id]
gender:[this.evaluationObject.gender],
firstName: new FormControl(this.evaluationObject.firstName,{
validators:Validators.required, updateOn: 'blur' }),
});
this.hardstopForm = this.formBuilder.group({
addressline1: new FormControl(this.evaluationObject.addressline1,{
validators:Validators.required, updateOn: 'blur' }),
});
this.eForm.get('gender').valueChanges.subscribe(val => {
this.hide(value);
});
this.hardstopForm.valueChanges.subscribe(val => {
this.validatehardstopformgroups();
});
this.eForm.valueChanges.subscribe(val => {
this.validateeform();
});
}
hide(value :string){
if(value == 'Yes'){
this.hidesection = true;
}
else if(value == 'No')
{
this.hidesection = false;
this.hardstopForm.reset();
}
}
# I am using the same validate function logic for all forms differently but the validation message array is common for all
hardstopformErrors={
addressline1:'' ,
}
formerrors={
gender:'',
firstName:''
}
CombinedvalidationMessages = {
}
validatehardstopformgroups(){
for (let field in this.hardstopformErrors) {
this.hardstopformErrors[field] = '';
//this.errors = [];
//this.checkAndAddErrors= '';
let input = this.hardstopForm.get(field);
console.log('input name = '+input);
console.log(this.submitted + " " + input.touched + " " + input.dirty + " " + input.invalid)
if ((this.submitted == true || input.touched || input.dirty) && input.invalid) {
for (let error in input.errors) {
console.log(this.submitted + " " + input.touched + " " + input.dirty + " " + input.invalid)
console.log('Error Occured on validation for ' + input + 'error is ' + error);
this.hardstopformErrors[field] = this.CombinedvalidationMessages[field][error];
}
}
}
this.errors.splice(0, this.errors.length);
for (let key in this.hardstopformErrors) {
console.log('key: ' + key + ', value: ' + this.hardstopformErrors[key]);
if (this.hardstopformErrors[key] != "" && this.hardstopformErrors[key] != null) {
this.checkAndAddErrors(this.hardstopformErrors[key]);
}
}
}
#HTML Structure
<div [formGroup]='eForm '>
''''''''''
<div [formGroup]='hardstopForm'>
'''''''
</div>
</div>