Angular 4 : Custom validator not being called

Viewed 6320

I have defined a custom validator for pan card number validation(https://en.wikipedia.org/wiki/Permanent_account_number).

function validatePan(): ValidatorFn {

 return (c: AbstractControl) => {   
            var regpan = /^([a-zA-Z]){5}([0-9]){4}([a-zA-Z]){1}?$/;

            if (!regpan.test(c.value)) {
                return {
                    validatepan: {
                      valid: false
                    }
                  };
            } else {
                return null;
            }
        }
}        

@Directive({
 selector: '[validatepan][ngModel], [validatepan][formControlName],    [validatepan][formControl]',
   providers: [
    { provide: NG_VALIDATORS, useExisting: forwardRef(() => PanValidator),     multi: true }
   ]
})
export class PanValidator implements Validator{
    validator: ValidatorFn;

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

  validate(c: FormControl) {
    console.log('here');
    return this.validator(c);
  }

}

I have registered the Directive in the declarations section of the module

 declarations: [
        ....
        PanValidator
   ],

I am using the directive as follows

<input type="text" class="form-control" name="testpan" id="field_testpan"
            [(ngModel)]="testval.testpan"
        validatepan />

But it is neither initializing the directive nor calling the validate function.

3 Answers

I had the same problem recently. Originally, I had just AppModule, where I declared both eg. SignupComponent and few validators which I used there to validate email etc. But then, I decided to move the SignupComponent and others to separate lazy loaded FeatureModule but forgot about the validators, which were still declared in the AppModule. I got no errors, some validators were even working - which was extremely confusing, but never ever was their validate method called.

So the solution was of course to declare them in FeatureModule instead of in AppModule. In Angular, you can declare service in the root module and they are accessible everywhere, but the validator directives (as all directives) need to be declared or imported to the module where they are being used. So if you plan on using them in other modules also, simply export them from the module (using exports property) as already suggested in the top answer and import the module where you need them.

Related