Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { Directive, Input } from '@angular/core';
- import { Validator, AbstractControl, NG_VALIDATORS, ValidatorFn } from '@angular/forms';
- import { emailValidator } from '../components/register/register.component';
- @Directive({
- selector: '[appEmail]',
- /**
- * Angular recognizes the directive's role in the validation process because the directive
- * registers itself with the NG_VALIDATORS provider,
- */
- providers: [{provide: NG_VALIDATORS, useExisting: EmailDirective, multi: true}]
- })
- export class EmailDirective implements Validator{
- @Input('appEmail') appEmail: string;
- //Auto Generated to be Implemented
- validate(c: AbstractControl): { [key: string]: any; } {
- if(this.appEmail){
- return emailValidator(new RegExp(this.appEmail))(c)
- }
- else{
- return null;
- }
- }
- registerOnValidatorChange?(fn: () => void): void {
- return null;
- }
- constructor() { }
- }
- // validates the email as per the Regex and returns
- // null --> Valid email format
- // emailInvalid --> Invalid email format
- export function emailValidator(nameRe: RegExp): ValidatorFn {
- return (control: AbstractControl): {[key: string]: any} => {
- let email=control.value
- const regResult = nameRe.test(email);
- return regResult ? null: {'emailInvalid': {value:email}};
- };
- }
Add Comment
Please, Sign In to add comment