Nemanja G
Nemanja G

Reputation: 1850

Validate Email in Angular 2

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.

Upvotes: 0

Views: 5749

Answers (2)

developer033
developer033

Reputation: 24874

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

Upvotes: 4

anoop
anoop

Reputation: 3822

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

<input 
id="email" 
type="text" 
pattern="^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$" 
required>

Upvotes: 2

Related Questions