0

If i want to create a directive which validates my email, how to do it?

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

@Directive({
  selector: '[appEmailValidator]'
})

export class EmailValidatorDirective {

  constructor() {}
}

Created the directive, but have no idea how to implement validation rules/messages.

developer033
  • 24,267
  • 8
  • 82
  • 108
Nemanja G
  • 1,760
  • 6
  • 29
  • 48
  • please refr to the answer, and try to implement it. It is better that a custom directive http://stackoverflow.com/questions/34072092/generic-mail-validator-in-angular2 – sainu May 05 '17 at 12:43

2 Answers2

4

First, you don't need to write your own validator.

Since Angular v4.0.0-beta6 there's a in-built email validator.

In order to use it, do the following:

<input 
  type="email"
  email
  name="emailField" 
  [(ngModel)]="email" 
  #emailField="ngModel">

DEMO

developer033
  • 24,267
  • 8
  • 82
  • 108
2

you can simply achieve it by pattern as well. Like:

<input 
id="email" 
type="text" 
pattern="^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$" 
required>
anoop
  • 3,812
  • 2
  • 16
  • 28
  • Yeah, I did all that,but I need to do the following somehow, and I am looking for the best solution: 1. Hide validation messages while typing 2. When u type and then delete - show msg: Email required 3. If you type and click outside the input while the email is not valid - msg = Email invalid 4. When u return into the field = hide all previous validation messages Kind of hard to do for myself :/ – Nemanja G May 05 '17 at 12:58