Angular 使用 FormBuilder 的反应式表单自定义验证

Angular reactive form custom validation using FormBuilder

我有一个名为 productionControlValidator 的自定义验证器函数。

如果我这样设置表单,一切正常:

this.validTest = new FormGroup({
    isdrawing: new FormControl(true),
    inventoryControl: new FormControl(null)
}, { validators: productionControlValidator });

但是,如果我使用这样的表单生成器设置表单:

this.validTest = this.fb.group({
    isdrawing: true,
    inventoryControl: null
}, { validators: productionControlValidator });

其中fb在构造函数中定义为private fb: FormBuilder, 那么验证不起作用。 "does not work",我的意思是表单的有效 属性 不正确,并且在控制台中我没有看到我期望的输出(使用第一种方法显示)。

我是不是在第二种方法中没有正确定义验证器(如果是这种情况,应该如何定义),或者 FormBuilder 是否有什么东西导致自定义验证器不可用?

了解更多信息 ---> DEMO

在组件中使用自定义验证服务

import {CustomValidationService } from './custom.service'

this.validTest = this.fb.group({
    name: [null, [Validators.required, CustomValidationService.nameValidator],
    inventoryControl: [null, [CustomValidation]]
});

您可以将 custom-validation-service 创建为:

@Injectable()
export class CustomValidationService {
    // Name validation 
        static nameValidator(control: FormControl) {
            if (control.value) {
                const matches = control.value.match(/^[A-Za-z\s]+$/);
                return matches ? null : { 'invalidName': true };
            } else {
                return null;
            }
        }
}

如果你想要组验证方法试试这个

 validateAllFormFields(formGroup: any) {         //{1}
    Object.keys(formGroup.controls).forEach(field => {  //{2}
      const control = formGroup.get(field);             //{3}
        if (control instanceof FormControl) {             //{4}
         control.markAsDirty({ onlySelf: true });
         } else if (control instanceof FormGroup) {        //{5}
         this.validateAllFormFields(control);            //{6}
      }
   });
}



save(data: any) {
    if (this.validTest.valid) {

    } else {
     this.validateAllFormFields(this.validTest);
  }
}

尝试使用验证器代替自定义验证器的验证器 文档:https://angular.io/api/forms/AbstractControl#root

(validator ValidatorFn | null) The function that determines the synchronous validity of this control.

this.validTest = this.fb.group({
    isdrawing: true,
    inventoryControl: null
}, { validator: productionControlValidator });

当 formGroup 中的 valueChanges 时触发表单验证。

示例如下:Reactive form custom validators

我们可以在更改表单的值后触发整个表单的表单验证。

示例如下class:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit  {

  validTest: FormGroup;
  hasError = false;

  constructor(private fb: FormBuilder) {
  }

  ngOnInit() {
    this.validTest = this.fb.group ({
      isdrawing: [true, [Validators.required]],
      inventoryControl: ['10', [Validators.required, Validators.pattern('[0-9]*')]]
    });

    this.validTest.valueChanges.subscribe(form => {
      if(form) {
        this.productionControlValidator(form);
      }
    });
  }

  private productionControlValidator(form) {
    // custom validations for form controls

    if(form) {
      this.hasError = this.validTest.invalid;
    }
  }
}

示例 html 模板:

<form [formGroup]="validTest">
  <input 
    type="checkbox"
    formControlName="isdrawing"/>

    <input
      type="text"
      formControlName="inventoryControl"
    />

    <div *ngIf="hasError">Form contains errors !!!</div>
</form>

基本上是 Angular 表单验证很简单。

在 app.component.ts 文件中:

你需要添加

import { FormGroup, FormBuilder, Validators } from '@angular/forms';

之后

ngOnInit() {

this.registerForm = this.formBuilder.group({

  email: ['', [Validators.required, Validators.email]],

  firstName: ['', Validators.required],

  lastName:['', Validators.required],

  address: ['', Validators.required],

})

}

就是这样。快乐编码