schacki schacki - 3 months ago 53
TypeScript Question

Angular2 custom validator not called

I have written a custom validation directive like that:

const DURATION_VALIDATOR = new Provider(
NG_VALIDATORS,
{useExisting: forwardRef(() => DurationDirective), multi: true}
);


@Directive({
selector: '[ngModel][duration], [formControl][duration]',
providers: [{
provide: NG_VALIDATORS,
useExisting: forwardRef(() => DurationDirective),
multi: true }]
})
export class DurationDirective implements Validator{
constructor(public model:NgModel){
console.error('init')
}
validate(c:FormControl) {
console.error('validate')
return {'err...':'err...'};
}
}


My Html looks like this:

<input
type="text"
[(ngModel)]="preparation.duration"
duration
required
>


My problem is that while the validator is initialized, i.e. 'init' is logged to console, the validate function is never called, i.e. 'validate' is never logged to the console, when typing into the input field. Since the validator is initialized, I assume that I "wired" up everything correctly. So what is missing?

Answer

My best bet is that you haven't bootstraped Angular with regards to forms:

import { App } from './app';
import { disableDeprecatedForms, provideForms } from '@angular/forms';

bootstrap(App, [
    // these are crucial
    disableDeprecatedForms(),
    provideForms()
  ]);

You can see this plunk - it does output "validate" to the console.

Comments