Jan_Botek
Jan_Botek

Reputation: 11

Custom validator not working in a template driven form

I wanted to add a custom validator to a template driven form in my angular project but the ngModel does not appear to register the custom validator. Do you know what might be the problem?

The validator

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

function usernameExistsFactory(): ValidatorFn {
  return (c: AbstractControl) => {
    let isValid = c.value === 'Juri';

    if (isValid) {
      return null;
    } else {
      return {
        usernameExists: true
      };
    }
  };
}
@Directive({
    selector: 'usernameExistsValidator',
    providers: [
      { provide: NG_VALIDATORS, useExisting: usernameExistsValidator, multi: true }
    ]
  })
  export class usernameExistsValidator implements Validator {
    validator: ValidatorFn;
    
    constructor() {
      this.validator = usernameExistsFactory();
    }
    
    validate(c: FormControl) {
      return this.validator(c);
    }
    
  }

The input element

<input (change)="log(name)" required usernameExistsValidator ngModel minlength="3" maxlength="32" name="name" #name="ngModel" type="text"  class="form-control" id="name">

The logged ngModel

Upvotes: 0

Views: 792

Answers (1)

AVJT82
AVJT82

Reputation: 73357

As you are using an attribute selector for your directive, we need to remember to use brackets [....], so modify your directive selector to:

selector: '[usernameExistsValidator]'

This applies in all cases when you want to use an attribute selector, so not only for this case.

Upvotes: 1

Related Questions