html - 当必填字段为空时,提交按钮点击服务器
问题描述
在 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);
}
});
}
我期待以下结果:
当我点击提交按钮时,当必填字段为空时,它不会被提交。一旦输入了所有必填字段,它就会被提交。
解决方案
如果表单无效,只需禁用按钮:
<button type="submit" value="Submit" tooltip="Submit" [disabled]="form.invalid">Submit</button>
推荐阅读
- python - 从数组中按一定顺序获取固定数量的数据
- python - 如何使用 Python 将特定选定行拆分为多行
- javascript - Apify - 如何在数据集中包含失败的结果
- search - 你能搜索整个 Youtube 成绩单内容吗?
- typescript - 为什么打字稿编译器允许这样做?
- visual-studio-code - Pub 在 VS Code 中不可访问,但在 CMD 中可访问
- sql - 为什么 SELECT 在死锁图中显示更新锁
- ios - 在 module.modulemap 中找不到头文件
- docker-compose - 将 amadeus API 与 Spring Boot 结合使用
- active-directory - 如何使用 Kerberos 进行 samba 身份验证