首页 > 解决方案 > 当必填字段为空时,提交按钮点击服务器

问题描述

在 Angular 7 中,我刚刚创建了一个包含一些字段和一个提交按钮的表单。在表格中,有一些必填字段。问题是当我点击提交按钮时,它会在必填字段为空时提交。

我将以下代码添加到 html 表单的所有输入字段中。

<div class="error" *ngIf="form.get('TournamentEndDate').invalid && 
form.get('TournamentEndDate').touched">*This Field is Required</div>


<form name="createForm" #tourDetailsData='ngForm' 
(ngSubmit)="saveEmployee(tourDetails)" enctype='multipart/form-data' 
novalidate>
<div class="form-group" [formGroup]="form">
                    <label class="lable label-default">Tournament 
Name<span style="color: red">*</span></label>
                    <input class="form-control" name='TournamentName' 
formControlName="TournamentName"
                        [(ngModel)]='tourDetails.TournamentName' required 
/>
                    <div class="error" 
*ngIf="form.get('TournamentName').invalid && 
form.get('TournamentName').touched">*This Field is Required</div>
                </div>
.....
.....
 <button type="submit" value="Submit" tooltip="Submit" >Submit</button>
                    <button type="reset" value="Reset" tooltip="Reset" 
(click)="reset()">Reset</button>
</form>

打字稿:

ngOnInit() {
    this.tourDetails.TournamentType = '';
    this.tourDetails.StarStatus = 0;
    this.form = this.formBuilder.group({
      Logo: [null, [Validators.required]], TournamentType: [null, 
Validators.required],
      TournamentName: [null, Validators.required], TournamentStartDate: 
[null, [Validators.required]],
      ....
      ....
    });
  }
....
....
saveEmployee(tourDetailsData: Usermodel) {
if (this.form.valid) {
  console.log('form submitted');
} else {
   this.validateAllFormFields(this.form);
   }
  ....
  .....

validateAllFormFields(formGroup: FormGroup) {
    Object.keys(formGroup.controls).forEach(field => {
    const control = formGroup.get(field);
    if (control instanceof FormControl) {
       control.markAsTouched({ onlySelf: true });
    } else if (control instanceof FormGroup) {
       this.validateAllFormFields(control);
     }
  });
}

我期待以下结果:

当我点击提交按钮时,当必填字段为空时,它不会被提交。一旦输入了所有必填字段,它就会被提交。

标签: htmlangulartypescript

解决方案


如果表单无效,只需禁用按钮:

 <button type="submit" value="Submit" tooltip="Submit" [disabled]="form.invalid">Submit</button>

推荐阅读