Angular 2 Angular 2 Forms Update Angular 2 Form - Custom Email/Password Validation


For live demo click..

App index ts

import {bootstrap} from '@angular/platform-browser-dynamic';
import {MyForm} from './my-form.component.ts';


Custom validator

import {Control} from @'angular/common';

export class CustomValidators {
  static emailFormat(control: Control): [[key: string]: boolean] {
    let pattern:RegExp = /\S+@\S+\.\S+/;
    return pattern.test(control.value) ? null : {"emailFormat": true};

Form Components ts

import {Component} from '@angular/core';
import {FORM_DIRECTIVES, NgForm, FormBuilder, Control, ControlGroup, Validators} from '@angular/common';
import {CustomValidators} from './custom-validators';

  selector: 'my-form',
  templateUrl: 'app/my-form.component.html',
  directives: [FORM_DIRECTIVES],
  styleUrls: ['styles.css']
export class MyForm {
  email: Control;
  password: Control;
  group: ControlGroup;
  constructor(builder: FormBuilder) { = new Control('', 
      Validators.compose([Validators.required, CustomValidators.emailFormat])
    this.password = new Control('',
      Validators.compose([Validators.required, Validators.minLength(4)])
    ); ={
      password: this.password
  onSubmit() {

Form Components HTML

<form [ngFormModel]="group" (ngSubmit)="onSubmit()" novalidate>

    <label for="email">Email:</label>
    <input type="email" id="email" [ngFormControl]="email">
    <ul *ngIf="email.dirty && !email.valid">
      <li *ngIf="email.hasError('required')">An email is required</li>

    <label for="password">Password:</label>
    <input type="password" id="password" [ngFormControl]="password">
    <ul *ngIf="password.dirty && !password.valid">
      <li *ngIf="password.hasError('required')">A password is required</li>
      <li *ngIf="password.hasError('minlength')">A password needs to have at least 4 characterss</li>

  <button type="submit">Register</button>