Guest User

Untitled

a guest
Apr 23rd, 2018
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.27 KB | None | 0 0
  1. import { Directive, Input } from '@angular/core';
  2. import { Validator, AbstractControl, NG_VALIDATORS, ValidatorFn } from '@angular/forms';
  3. import { emailValidator } from '../components/register/register.component';
  4.  
  5. @Directive({
  6. selector: '[appEmail]',
  7. /**
  8. * Angular recognizes the directive's role in the validation process because the directive
  9. * registers itself with the NG_VALIDATORS provider,
  10. */
  11. providers: [{provide: NG_VALIDATORS, useExisting: EmailDirective, multi: true}]
  12. })
  13. export class EmailDirective implements Validator{
  14. @Input('appEmail') appEmail: string;
  15.  
  16. //Auto Generated to be Implemented
  17. validate(c: AbstractControl): { [key: string]: any; } {
  18. if(this.appEmail){
  19. return emailValidator(new RegExp(this.appEmail))(c)
  20. }
  21. else{
  22. return null;
  23. }
  24. }
  25.  
  26. registerOnValidatorChange?(fn: () => void): void {
  27. return null;
  28. }
  29. constructor() { }
  30. }
  31. // validates the email as per the Regex and returns
  32. // null --> Valid email format
  33. // emailInvalid --> Invalid email format
  34. export function emailValidator(nameRe: RegExp): ValidatorFn {
  35. return (control: AbstractControl): {[key: string]: any} => {
  36. let email=control.value
  37. const regResult = nameRe.test(email);
  38. return regResult ? null: {'emailInvalid': {value:email}};
  39. };
  40. }
Add Comment
Please, Sign In to add comment