提交表单时验证出错



我有一个表单,在表单内部我在选择下拉菜单时显示了一个文本框我调用一个表单数组,我得到多个文本框。当我提交我的表单显示无效,即使我给所有字段的值。




<input type="text" class="form-control" placeholder="Type" formControlName="type">                                      
<select class="Dropdown" formControlName="category" >
<option >Select Category</option>
<option  *ngFor="let list of dropdownitems" [value]="list.id" >{{list.name}}</option>
</select> 
<ng-container *ngIf="optionValue == '3'">

<input type="text" formControlName="listItem" class="form-control" placeholder="enter dropdownlist items"> 
<small class="errormessage" *ngIf="submitted && addForm.controls.listItem.hasError('required')">
Category is required 
</small>
<a (click)="addGroup()">Add New Textfield</a>
</ng-container>

<span formArrayName="times" *ngFor="let time of addForm.controls.times?.value; let i = index;">                          
<span [formGroupName]="i">                         
<input type="text" class="form-control" formControlName="lists" placeholder="enter dropdown options">  
</span>              

在这里,我正在验证所有字段。onSubmit()函数,如果表单无效,我将显示一个警告。请纠正我的代码,并帮助我实现这个功能。

ngOnInit(): void {
this.addForm = this.formBuilder.group({
name: ['', [Validators.required, Validators.pattern('[a-zA-Z# ]*')]],
times: this.formBuilder.array([])
}); 
console.log(this.addForm.value);
}
public dropdownitems = [{
name: "A",
id: 1
},{
name: "B",
id: 2
},{
name: "B",
id: 3   
},{
name: "D",
id: 4    
}]
onSubmit(){
this.submitted = true;
if (this.addForm.invalid) {
alert ('Please fill up complete details');
return;
}
console.log(this.addForm.value);   
}

value = this.formBuilder.group({
lists: ['', Validators.required],
});

addGroup() {
const val = this.formBuilder.group({
lists: ['', Validators.required],
});
const form = this.addForm.get('times') as FormArray;
form.push(val);
}
removeGroup(index) {
const form = this.addForm.get('times') as FormArray;
form.removeAt(index);
}
}

问题是,即使字段隐藏在模板(HTML)中,它们在表单中也被定义为required

您需要有条件地添加和删除表单字段,或者您需要将它们设置为enabled/disabled以忽略required标志。

在这里分享固定的Stackblitz与一个可能的解决方案和小改进(删除ngModel

您在此线程中提出了类似的问题隐藏字段的表单验证

相关内容

  • 没有找到相关文章

最新更新