Last active
February 18, 2017 20:42
-
-
Save tomlobato/558f81c842d767847f3c5b6f6b8f7476 to your computer and use it in GitHub Desktop.
Angular 2 equal-validator.directive.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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