Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.