import { Directive, OnInit } from '@angular/core';

import { AbstractControl, ValidatorFn, FormControl, Validator, NG_VALIDATORS } from '@angular/forms';

@Directive({
    selector: '[oneitemail][ngModel]',
    providers: [
        { provide: NG_VALIDATORS, useExisting: EmailValidatorDirective, multi: true }
    ]
})
export class EmailValidatorDirective implements Validator {
    constructor() { }

    validate(c: AbstractControl): { [key: string]: any } {
        if (!c.value || /^[_a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/.test(c.value)) {
            return null;
        } else {
            return {
                email: {
                    valid: false
                }
            };
        }
    }
}