首页 > 解决方案 > Angular Ionic - 仅当某个字段是某个值时才验证表单

问题描述

我很确定这很容易做到,但我无法在任何地方找到解决方案。

我有一个formGroup被调用的议程。在启用提交之前,所有字段都是必填且有效的。我还希望最后一个字段仅在它等于用户输入的某个数字(由 定义solution)时才有效。我简化了下面的代码:

<form (ngSubmit)="submitForm()" [formGroup]="agenda" class="bodytext">
  <ion-input type="text" name="email" formControlName="email" required></ion-input>
  <ion-input type="text" name="userSolution" formControlName="userSolution" required></ion-input>
  <ion-button type="submit" expand="block" [disabled]="agenda.invalid">Submit</ion-button>
</form>

然后在 ts 文件中有我的构造函数:

constructor( http: HttpClient, private formBuilder: FormBuilder) {
    this.http = http;
    this.agenda = this.formBuilder.group({
      email: [''],
      userSolution: [''],
    });
  }

标签: angularionic-framework

解决方案


我在 stackblitz 上创建了一个工作示例,当条件为真时,我假设数字为 20。您还可以在初始化表单时使用所需的验证器。

我使用了一个自定义验证器,它返回错误名称作为键,{errorName: true}如果条件不匹配,则返回布尔值 true 作为值,并且该错误名称可用于验证错误消息。

export class AppComponent implements OnInit {
  agenda: FormGroup;
  solution = 20;

  constructor(private formBuilder: FormBuilder) {}

  ngOnInit() {
    this.initForm();
  }

  initForm() {
    this.agenda = this.formBuilder.group({
      email: ["", Validators.required],
      userSolution: ["", [Validators.required, this.myValidator(this.solution)]]
    });
  }

  myValidator(num: number): ValidatorFn {
    return (control: AbstractControl): { [key: string]: boolean } | null => {
      if (
        control.value !== undefined &&
        (isNaN(control.value) || control.value != num)
      ) {
        return { notEqual: true };
      }
      return null;
    };
  }

}

形式-

<form [formGroup]="agenda" class="bodytext">
  <input type="text" name="email" formControlName="email">
  <input type="text" name="userSolution" formControlName="userSolution">
  <button type="submit" expand="block" [disabled]="agenda.invalid">Submit</button>
</form>

演示链接 - stackBlitz


推荐阅读