【发布时间】:2019-04-08 11:34:27
【问题描述】:
我有一些设置了不同验证规则的输入字段。 但我也想在提交时一次对所有字段添加一些验证,或者禁用提交按钮,如果上面有任何错误。
但是,我并没有从一开始就将所有输入都放在表单标签中,现在我遇到了一些麻烦。我对这一切都很陌生,所以你能帮帮我吗?有没有办法解决它,而无需重新创建所有表单? :(
我已经尝试添加:
<form #stepOneForm="ngForm">
<button type="submit [disabled]="!stepOneForm.form.valid" mat-button matStepperNext>Go to next step</button>
但它没有帮助......
我的代码如下:
HTML
<!-- Name -->
<mat-form-field class="dcp-input-field">
<input matInput placeholder="Name" [formControl]="name" [errorStateMatcher]="matcher">
<mat-hint>Please enter your name</mat-hint>
<mat-error *ngIf="name.hasError('required')">
This is <strong>required</strong> field
</mat-error>
</mat-form-field>
<!-- DoB -->
<mat-form-field class="dcp-input-field">
<input matInput [matDatepicker]="dp" placeholder="Date of Birth" [formControl]="dob" [errorStateMatcher]="matcher">
<mat-datepicker-toggle matSuffix [for]="dp"></mat-datepicker-toggle>
<mat-datepicker #dp></mat-datepicker>
<mat-hint>Please enter your date of birth</mat-hint>
<mat-error *ngIf="dob.hasError('required')">
This is <strong>required</strong> field
</mat-error>
</mat-form-field>
<!-- PolicyNo -->
<mat-form-field class="dcp-input-field">
<input matInput placeholder="Policy number" [formControl]="policyNo" [errorStateMatcher]="matcher">
<mat-hint>Please enter your Policy number</mat-hint>
<mat-error *ngIf="policyNo.hasError('required')">
This is <strong>required</strong> field
</mat-error>
<mat-error *ngIf="policyNo.hasError('minlength')">
The value is <strong>too short</strong>
</mat-error>
</mat-form-field>
TS
export class MyErrorStateMatcher implements ErrorStateMatcher {
isErrorState(
control: FormControl | null,
form: FormGroupDirective | NgForm | null
): boolean {
const isSubmitted = form && form.submitted;
return !!(
control &&
control.invalid &&
(control.dirty || control.touched || isSubmitted)
);
}
}
name = new FormControl("", [Validators.required]);
dob = new FormControl("", [Validators.required]);
policyNo = new FormControl("", [
Validators.required,
Validators.minLength(6)
]);
matcher = new MyErrorStateMatcher();
谢谢你,对不起菜鸟问题! ;)
【问题讨论】:
-
我也尝试将我所有的 FormControls 插入到一个 FormGroup 中,但是在那之后所有的单一验证都被破坏了,所以看起来我又做错了什么......
-
您想在材料步进器的多步中使用单个表单并希望在表单有效之前禁用按钮?
-
实际上,我想要几个表格按步骤划分,是的 - 如果有一些错误,我想禁用“转到下一步”按钮。因此,如果所有步骤都已验证,则无需将验证设置为整体流程。
标签: angular validation angular-material