【问题标题】:How to validate a form based on a condition in angular 6?如何根据角度 6 中的条件验证表单?
【发布时间】:2019-01-27 10:57:49
【问题描述】:

我有一个下拉菜单。根据下拉列表的选择,我需要显示一些列以及每个选择通用的现有列。

My html:

<mat-form-field class="col-xl-6 col-lg-3 col-md-3 col-sm-12 col-xs-12">
      <mat-select [(ngModel)]="selectedValue" placeholder="EntityName" (selectionChange)="changeEntity($event.value)" [ngModelOptions]="{standalone: true}">
        <mat-option *ngFor="let type of types" [value]="type.viewValue">
          {{type.viewValue}}
        </mat-option>
      </mat-select>
    </mat-form-field>

 <div *ngIf="selectedValue === 'One'" class="row formGroup">
    <mat-form-field class="example-full-width" class="col-xl-6 col-lg-3 col-md-3 col-sm-12 col-xs-12">
      <input matInput placeholder=" OneID" type="text" id="oneid" formControlName="oneid">
    </mat-form-field>
  </div>

  <div class="row formGroup">
    <mat-form-field class="example-full-width" class="col-xl-6 col-lg-3 col-md-3 col-sm-12 col-xs-12">
      <input matInput placeholder="Name" type="text" id="commonname" formControlName="commonname">

      </div>
    </mat-form-field>
<div class="formGroup" *ngIf="selectedValue === 'Two'"
    <mat-form-field class="example-full-width" class="col-xl-6 col-lg-3 col-md-3 col-sm-12 col-xs-12">
      <input matInput  type="text" id="username" formControlName="twoname">
    </mat-form-field>
 </div>

我的 Ts 文件:

  myForm = this.fb.group( {
    oneid: ['', Validators.required],
     commonname: ['', Validators.required],
     oneid: ['', Validators.required],
     twoname:['',Validators.required],

   })

 get f() {

    return this.myForm.controls;
 }
 if (this.myForm.invalid) {
  console.log("invalid");
  return;
} 

所以我的疑问是如何进行验证?如果我为单独的字段保留表单控件名称,我的表单返回无效。如何在没有单独的表单控件名称的情况下对此嵌套输入进行验证并获取每个输入字段的值?请指导我。

【问题讨论】:

  • 第一眼看不懂你在问什么!
  • 你能在 stackblitz 中制作这个吗
  • 您可以使用 get() 单独检查表单属性的验证,例如 this.myForm.get("oneid").invalid
  • @Vignesh 我评论了 stackblitz 链接。请检查。

标签: angular forms angular6


【解决方案1】:

您不需要避免使用表单控件名称。您需要的是动态验证。

在您的 onSubmit() 方法中动态更改验证规则。 你可以这样写代码:

if(some-condition) {
this.entityForm.get('eid').clearValidators();
this.entityForm.get('principalEntity').clearValidators();
this.entityForm.get('tel').clearValidators();
this.entityForm.get('rilid').clearValidators();

this.entityForm.get('eid').updateValueAndValidity();
this.entityForm.get('principalEntity').updateValueAndValidity();
this.entityForm.get('tel').updateValueAndValidity();
this.entityForm.get('rilid').updateValueAndValidity();
}

请注意,您需要通过调用clearValidators(),根据某些条件清除特定控件的验证规则。 此外,您需要致电updateValueAndValidity() 让他们重新评估。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-06
    • 1970-01-01
    • 2019-06-13
    • 2019-02-03
    • 2019-01-17
    • 2019-05-19
    • 2020-01-27
    • 1970-01-01
    相关资源
    最近更新 更多