javascript - 自定义验证器不调用 Angular 2 中的每个按键

标签 javascript angular validation angular-reactive-forms custom-validators

我在 Angular 2 中为 Reactive 表单编写了一个自定义验证器。但是我的函数只验证文本字段中的第一次按键操作。这里我的自定义函数应该验证每个按键。任何人都可以纠正我。

这是我在类里面调用自定义函数的方式。

  'customerNumberOwner': new FormControl('', [CustomValidators.CustomerNumberCustomValidation(6,8)]),

这是我的自定义函数。

//Custom validator for Customer number owner
  static CustomerNumberCustomValidation(min: number, max: number): ValidatorFn {
    return (c: AbstractControl): { [key: string]: boolean } | null => {
      var reg=/[^A-Za-z0-9]+/;
        if(c && (c.value !== '')){
          const str=c.value;
         
              if (str.match(reg) || str.length<min ||str.length>max ){
                console.log('Invalid')
              return { 
                  'CustomerNumberCustomValidation' : true
                   };
              }
        
          }
      
      
      return null;
    };
}

最佳答案

希望对你有帮助

DEMO

HTML:

<h1>
    Try Reactive Form Validation with custom validation
</h1>

<form [formGroup]="basicForm">
    <input type="text" minlength="10" maxlength="10" formControlName="name" placeholder="Enter Name For Validation" />
    <p *ngIf="basicForm.get('name').hasError('required') && basicForm.get('name').touched">Required</p>
    <p *ngIf="basicForm.get('name').hasError('minlength')">Min Length 10</p>
    <p *ngIf="basicForm.get('name').hasError('maxlength')">Max Length 10</p>
    <p *ngIf="basicForm.get('name').hasError('CustomerNumberCustomValidation')">Pattern Invalid /[^A-Za-z0-9]+/</p>
</form>

应用程序组件.ts:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { CustomValidatorService } from './custom-validator.service'

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

  basicForm: FormGroup;


  ngOnInit() {
    this.createForm();
  }

  constructor(private fb: FormBuilder) {
  }

  createForm() {
    this.basicForm = this.fb.group({
      name: this.fb.control(null, [Validators.required, Validators.minLength(10), CustomValidatorService.CustomerNumberCustomValidation])
    })
  }
}

自定义验证器.service.ts:

import { Injectable } from '@angular/core';
import { AbstractControl, FormControl, ValidatorFn } from '@angular/forms';

@Injectable()
export class CustomValidatorService {

  constructor() { }

  static CustomerNumberCustomValidation(control: FormControl) {
    var reg = /[^A-Za-z0-9]+/;
    if (control.value) {
      const matches = control.value.match(reg);
      return matches ? null : { 'CustomerNumberCustomValidation': true };
    } else {
      return null;
    }
  }
}

关于javascript - 自定义验证器不调用 Angular 2 中的每个按键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51587089/

相关文章:

javascript - 如何使用 *ngFor 循环 [object Object]

Javascript 不验证表单中的密码

javascript - 如何检查我的对象是否存在于 javascript map 中?

javascript - 使用 for 循环索引填充请求 Promise uri

javascript - 如何在combineReducers中使用根级别的初始状态?

javascript - 如果对象包含字符串数组的每个元素,则返回 true 的算法

c++ - 将字符从输入转换为字符串

javascript - 隐藏在 JS 幻灯片后面的下拉菜单

angular - vscode : manually recheck for errors/problems (angular 2)

python - Django 值错误 : Missing staticfiles manifest entry for 'inline.bundle.js' runserver