Skip to content

Instantly share code, notes, and snippets.

@tomlobato
Last active February 18, 2017 20:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tomlobato/558f81c842d767847f3c5b6f6b8f7476 to your computer and use it in GitHub Desktop.
Save tomlobato/558f81c842d767847f3c5b6f6b8f7476 to your computer and use it in GitHub Desktop.
Angular 2 equal-validator.directive.ts
import { Directive, forwardRef, Attribute } from '@angular/core';
import { Validator, AbstractControl, NG_VALIDATORS } from '@angular/forms';
// variation from https://plnkr.co/edit/KgjSTj7VqbWMnRdYZdxM?p=preview
@Directive({
selector: '[validateEqual][formControlName],[validateEqual][formControl],[validateEqual][ngModel]',
providers: [
{ provide: NG_VALIDATORS, useExisting: forwardRef(() => EqualValidator), multi: true }
]
})
export class EqualValidator implements Validator {
constructor(@Attribute('validateEqual') public validateEqual: string,
@Attribute('reverse') public reverse: string,
){}
validate(c: AbstractControl): { [key: string]: any } {
let other = c.root.get(this.validateEqual);
if (!other) return null;
return this.reverse === 'true' ?
this.validateReverse(c, other) : this.validateNoReverse(c, other);
}
validateNoReverse(c: AbstractControl, other: AbstractControl): { [key: string]: any } {
return other.value === c.value ?
null : {validateEqual: true}
}
validateReverse(c: AbstractControl, other: AbstractControl): { [key: string]: any } {
if (c.value === other.value) {
delete other.errors['validateEqual'];
if (Object.keys(other.errors).length == 0) {
other.setErrors(null);
};
} else {
other.setErrors(Object.assign(other.errors, {validateEqual: true}));
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment