Custom validator is not calling for each key press in Angular 2

3k Views Asked by At

I wrote a custom validator for Reactive forms in Angular 2.But my function is validating only first key press in the text field. Here my custom function supposed to validate each key press. Could any one please correct me.

This is the way I am calling custom function in my class.

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

Here is my custom function.

//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;
    };
}

1

There are 1 best solutions below

0
Akj On

I hope this will help

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>

app.component.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])
    })
  }
}

custom-validator.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;
    }
  }
}