在角度7中提交时无法验证反应形式

时间:2019-03-28 15:05:23

标签: angular angular2-forms

我正在尝试提交空白表单以触发验证。我还研究了以下主题,但未能实现。它没有错误或输出

在Submit函数上,我正在调用以下函数以将表单输入标记为已触摸

validateAllFields(formGroup: FormGroup) {
Object.keys(formGroup.controls).forEach(field => {
  const control = formGroup.get(field);
  if (control instanceof FormControl) {
    control.markAsTouched({ onlySelf: true });
    control.updateValueAndValidity();
  } else if (control instanceof FormGroup) {
    this.validateAllFields(control);
  }
});
}

表单组初始化

buildForm(): void {
this.userForm = this.formBuilder.group({
  first_name: [
    this.user.first_name,
    Validators.compose([
      Validators.required,
      Validators.minLength(2),
      Validators.maxLength(20)
    ])
  ],
  middle_name: [this.user.middle_name],
  last_name: [
    this.user.last_name,
    Validators.compose([
      Validators.required,
      Validators.minLength(2),
      Validators.maxLength(20)
    ])
  ],
  email: [
    this.user.email,
    Validators.compose([Validators.required, Validators.email])
  ],
  mobile_number: [
    this.user.mobile_number,
    Validators.compose([
      Validators.required,
      Validators.maxLength(10),
      Validators.pattern('^[1-9][0-9]{9,9}$'),
      validMobileNumber
    ])
  ],
  password: [
    this.user.password,
    Validators.compose([Validators.required, Validators.minLength(8)])
  ],
  c_password: [
    this.user.c_password,
    Validators.compose([Validators.required, confirmPassword])
  ],
  user_type_id: [this.user.user_type_id, Validators.required]
});
this.userForm.valueChanges.subscribe(data => this.onValueChanged(data));
}

0 个答案:

没有答案