首页 文章

我的自定义验证器不起作用,反应形式Angular 6

提问于
浏览
0

我正在尝试验证输入,检查我正在注册的文章是否存在...所以...我有一个检查我的数据库的方法,然后我在变量中设置一个布尔值 .

然后我将此变量传递给验证器......但是某些东西不起作用 .

验证功能:

validateRef(controlref: boolean): ValidatorFn {
    return () => {

        if ( controlref == true  ) {
            return { 'validref': true };
        } 

        if (controlref == false) {
          return { 'validref': false}
        }
    };

我的表格:

constructor( private fb: FormBuilder ) {

    this.createForm();

  }

  createForm() {
    this.dataForm = this.fb.group({
      ref: ['', [Validators.required, this.validateRef(this.controlref)]],
    })
  }
}

我传递给函数的变量,我已经检查并且正在工作......但是this.data.controls.ref.errors总是为null .

这里STACKBLITZ

你们能指导我吗?谢谢

1 回答

  • 0

    HTML

    DEMO

    <form [formGroup]="dataForm">
        <input placeholder="Enter Something" formControlName="ref">
        <div *ngIf="dataForm.get('ref').hasError('invalidRef')">
            the data is not entered
        </div>
    </form>
    

    零件:

    ngOnInit() {
        this.dataForm = this.fb.group({
          ref: ['', [Validators.required, CustomvalidatorService.validateRef]],
        })
      }
    

    定制validator.service.ts:

    import { Injectable } from '@angular/core';
    import { AbstractControl, FormControl } from '@angular/forms';
    
    
    @Injectable()
    export class CustomvalidatorService {
    
      constructor() { }
    
      static validateRef(control: FormControl) {
        if (!control.value) {
          return { 'invalidRef': true };
        } else {
          return null;
        }
      }
    
    }
    

相关问题