【问题标题】:Multiple stage form validation angular多阶段表单验证角度
【发布时间】:2021-11-03 21:15:04
【问题描述】:

我正在处理在多个阶段进行验证的表单,很少有元素正常验证,很少有元素在模糊时验证,其他元素在提交时验证。验证工作不正常。如果有人知道更好的处理方法,请告诉我。谢谢

这是我的代码:

constructor(
  private changeDetectorRef: ChangeDetectorRef,
  private el: ElementRef,
  private _snackBar: MatSnackBar ) {
  this.form = new FormGroup({});
  this.form.addControl(`firstname`, new FormControl(''));
  this.form.addControl(`lastname`, new FormControl(''));
  this.form.addControl(`title`, new FormControl('', 
  Validators.compose([Validators.required])));
this.form.addControl(
  `email`,
  new FormControl(
    '',
    Validators.compose([
      Validators.required,
      Validators.pattern('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$'),
    ])
  )
);
this.form.addControl(
  `phoneNumber`,
  new FormControl('', Validators.compose([Validators.required, Validators.pattern('^[0-9]*$')]))
);
this.form.addControl(
  `termsAndConditions`,
  new FormControl('', Validators.compose([Validators.required]))
);

this.changeDetectorRef.markForCheck();
}


addValidation() {
this.form.controls['firstname'].setValidators([Validators.required, Validators.minLength(2)]);
this.form.controls['lastname'].setValidators([Validators.required, Validators.minLength(2)]);
 }
 removeValidation() {
   this.form.controls['firstname'].setValidators([]);
   this.form.controls['lastname'].setValidators([]);
}

 onSubmit() {
    this.addValidation();
    // rest of my logic
}

onCancelBtnClick() {
  this.form.reset();
  this.removeValidation();
}

【问题讨论】:

    标签: angular forms validation


    【解决方案1】:

    有一种更清洁的方法。在构造函数中对代码进行一些更改,然后您将不需要 addValidation 和 removeValidation 方法。例如,我们在提交时对名字和姓氏应用验证,在模糊时对电子邮件应用验证。

      this.form.addControl(`firstname`, new FormControl('', {
      validators: Validators.compose([Validators.required, Validators.minLength(2)]), updateOn: 'submit'
    }));
    this.form.addControl(`lastname`, new FormControl('', {
      validators: Validators.compose([Validators.required, Validators.minLength(2)]), updateOn: 'submit'
    }));
    this.form.addControl(`title`, new FormControl(''));
    this.form.addControl(
      `email`,
      new FormControl(
        '',
        Validators.compose([
        '', {
        validators: Validators.compose([
          Validators.required,
          Validators.pattern('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$'),
        ])
        ]), updateOn: 'blur'
      }
      )
    );
    

    【讨论】:

      猜你喜欢
      • 2018-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多