Advertisement
Guest User

Untitled

a guest
Sep 16th, 2019
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.95 KB | None | 0 0
  1. import { Directive } from '@angular/core';
  2. import { Validator, NG_VALIDATORS, ValidatorFn, FormControl } from '@angular/forms';
  3.  
  4. @Directive({
  5. selector: '[appEmailvalidator]',
  6. providers: [
  7. {
  8. provide: NG_VALIDATORS,
  9. useClass: EmailvalidatorDirective,
  10. multi: true
  11. }
  12. ]
  13. })
  14. export class EmailvalidatorDirective implements Validator {
  15.  
  16. validator: ValidatorFn;
  17. constructor() {
  18. this.validator = this.emailValidator();
  19. }
  20.  
  21. validate(c: FormControl) {
  22. return this.validator(c);
  23. }
  24.  
  25. emailValidator(): ValidatorFn {
  26. return (control: FormControl) => {
  27. if (control.value != null && control.value !== '') {
  28. let isValid = /^[_a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/.test(control.value);
  29. if (isValid) {
  30. return null;
  31. } else {
  32. return {
  33. emailvalidator: { valid: false }
  34. };
  35. }
  36. } else {
  37. return null;
  38. }
  39. };
  40. }
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement