我在该项目中的最后一个问题是,一旦所有输入字段为空,部分填充或无效,并且如果用户错误地单击了提交按钮,则来自输入字段的无效数据将被添加到主表中。
我尝试过的代码是:
打字稿:
onSubmit(){
this.submitted=true;
if(this.formName.invalid){
return;
}
if(this.submitted){
this.showModal=false
}
}
请指导我有关我所缺少的内容。
编辑1:按照建议,我已经插入了所有必需的验证,并且它们对于所有输入字段都工作得很好。我的问题是,如果用户错误地提交了按钮,默认情况下也会将无效的输入数据添加到输出中。 请相应地进行指导。
答案 0 :(得分:2)
您必须先验证您的表格,然后才能提交。有两种方法可以做到这一点:
在Component.ts
onSubmit() {
if(this.form.valid) {
/* write your code here */
}
}
在Component.html
中<button type="submit" class="btn btn-default" [disabled]="!form.valid">Submit</button>
答案 1 :(得分:1)
创建表单时必须使用验证器。
this.registerForm = this.formBuilder.group({
title: ['', Validators.required],
firstName: ['', Validators.required],
lastName: ['', Validators.required],
email: ['', [Validators.required, Validators.email]],
password: ['', [Validators.required, Validators.minLength(6)]],
confirmPassword: ['', Validators.required],
acceptTerms: [false, Validators.requiredTrue]
});
在这里,registerForm仅在满足所有指定的验证时才有效。在这里,所有字段都通过添加所需的验证器来按要求进行。密码字段的最小长度也为6。
然后该表单仅在验证成功后才有效。
然后在提交功能中,您可以使用来检查表单的有效性
submit(){
if(!this.registerForm.valid){
return false;
}
else {
//process you request
}
}
答案 2 :(得分:0)
使用以下代码验证提交时的反应形式。
HTML
select id, max(time) as time, 'F' as status
from t
group by id
having sum(case when status = 'T' then 1 else 0 end) > 0 and
max(time) = max(case when status 'F' then time end);
TypeScript
<form (ngSubmit)="onSubmit()" [formGroup]="myReactiveForm">
<div formGroupName="userDetail">
<div class="form-group">
<label for="FirstName">First Name*</label>
<input type="text" class="form-control" id="txtFName" formControlName="fname"
placeholder="First Name">
<small
*ngIf="!myReactiveForm.get('userDetail.fname').valid && myReactiveForm.get('userDetail.fname').touched"
class="text-danger">First name required.</small>
</div>
</form>
提交方法
export class Form2Component implements OnInit {
myReactiveForm: FormGroup;
}