Directive for validation the input value

2.4k views Asked by At

I created the directive for validating the input value. I need that on input some characters my input/form become ivalid. Here is my code, but it is not working.

import {Directive, Input} from '@angular/core';
import {AbstractControl, NG_VALIDATORS, ValidationErrors} from '@angular/forms';

const regExp = new RegExp('(>|<)+');

@Directive({
    selector: '[validator]',
    providers: [{
        provide: NG_VALIDATORS,
        useExisting: ValidatorDirective,
        multi: true
    }]
})

export class ValidatorDirective {
    @Input('validator') input;

    constructor() {

    }

    validate (control: AbstractControl): ValidationErrors {
        const value = control.value;
        const isValid = regExp.test(value);

        return isValid ? null : {
            validator: {
                valid: false
            }
        };
    }
}

Thank you for your help. Have a nice day.

1

There are 1 answers

8
Rahul Singh On BEST ANSWER

Using [validator][ngModel] will do the trick in your case as you don't need to have an input for this directive

Like this

import {AbstractControl, ValidatorFn, Validator, FormControl, NG_VALIDATORS} from "@angular/forms";
import {Directive} from '@angular/core';


const regExp = new RegExp('(>|<)+');
function validateregex(): ValidatorFn {
  return (c : AbstractControl) => {

    const isValid = regExp.test(c.value);
    console.log("Valid"+isValid);
    //let isValid = c.value === 'Rahul';
    if(isValid){
      return null;
    }else{
      return {
        validator: {
          valid: false
        }
      };
    }

  }
}

@Directive({
  selector: '[regex][ngModel]',
  providers: [{
    provide: NG_VALIDATORS, useExisting: ValidatorDirective, multi: true
  }]
})

export class ValidatorDirective implements Validator{

  validator: ValidatorFn;

  constructor() {
    this.validator = validateregex();
  }

  validate(c: FormControl) {
    return this.validator(c);
  }

}

Add this directive to declarations array of Ngmodule ValidatorDirective,

The working example of the same link.