Skip to content

Instantly share code, notes, and snippets.

@fabriciobastian
Created October 14, 2019 12:54
Show Gist options
  • Save fabriciobastian/08963aada51c22ea4b90bc97d8317a62 to your computer and use it in GitHub Desktop.
Save fabriciobastian/08963aada51c22ea4b90bc97d8317a62 to your computer and use it in GitHub Desktop.
Angular validation directive for template-driven forms
import { Directive, Input, OnChanges, SimpleChanges } from '@angular/core';
import { NG_VALIDATORS, Validator, AbstractControl, ValidationErrors } from '@angular/forms';
@Directive({
selector: '[greaterThan]',
providers: [
{
provide: NG_VALIDATORS,
useExisting: GreaterThanValidator,
multi: true,
},
],
})
export class GreaterThanValidator implements Validator, OnChanges {
@Input() public greaterThan: number;
private _onChange: () => void;
validate(control: AbstractControl): ValidationErrors | null {
if (this.greaterThan <= control.value) {
return null;
}
return { 'greaterThan': true };
}
registerOnValidatorChange(fn: () => void): void {
this._onChange = fn;
}
ngOnChanges(changes: SimpleChanges): void {
if ('greaterThan' in changes) {
if (this._onChange) {
this._onChange();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment