12/08/2018, 15:18

Form Validation in Angular 2

AngularJS is one of the greatest frameworks that provides us with a great deal of flexibility and power for building Single Page Applications. One of the magnificent features of AngularJS is the Form Validation . Through the act of decorating input fields with ng- attributes, angular ...

AngularJS is one of the greatest frameworks that provides us with a great deal of flexibility and power for building Single Page Applications. One of the magnificent features of AngularJS is the Form Validation. Through the act of decorating input fields with ng- attributes, angular validation is triggered automatically and let users know whether if an input field or a form is valid or not.

AngularJS 2 has been considered an ground-breaking change for developers in comparison with its v1 counterpart. In this article, let check out how the form validation mechanism functions.

In AngularJS 1.x, each time users change values of a form, AngularJS constantly updates the states of the form and the input fields. Forms and input fields have their respective state (such as $untouched, $pristine, $dirty, $valid, $invalid,..., which you can review in the reference link at the bottom of my article). All of these states are properties of AngularJS FormController.

 
<div class="container">
  <div class="row">
    <div class="col-md-8">
      <form class="form-horizontal" name="userForm" ng-submit="onSubmit()" novalidate>
        <div class="form-group">
          <label class="col-md-3" for="name">Name</label>
          <div class="col-md-9">
            <input
              class="form-control"
              type="text"
              id="name"
              name="name"
              ng-min-length="8"
              ng-max-length="20"
              required
            >
            <div ng-if="userForm.name.$touched && userForm.name.$error" class="alert alert-danger">
                <span ng-if="userForm.name.$error.required">Username is required!</span>
                <span ng-if="userForm.name.$error.minlength">Username should be longer than 8 characters!</span>
                <span ng-if="userForm.name.$error.maxlength">Username should be no longer than 20 characters!</span>
            </div>
          </div>
        </div>
        <div class="form-group text-center">
          <button type="submit" name="button" class="btn btn-primary" ng-disabled="!userForm.$valid">Submit</button>
        </div>
      </form>
    </div>
  </div>
</div>

2.1. Template-driven Form

In AngularJS 2, we can achieve the same output. But with just "a little more" implementation effort and different syntax:

// form-demo.module.ts
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';

import { FormDemoComponent } from './form-demo/form-demo.component';

@NgModule({
  imports: [ FormsModule ],
  declarations: [ FormDemoComponent ],
  exports: [ FormDemoComponent ]
})
export class FormDemoModule { }
 
<div class="container">
  <div class="row">
    <div class="col-md-8">
      <form class="form-horizontal" #userForm="ngForm" ngSubmit="onSubmit()" novalidate>
        <div class="form-group">
          <label class="col-md-3" for="name">Name</label>
          <div class="col-md-9">
             <input 
                 class="form-control"
                  type="text"
                  id="name"
                  name="name"
                  minlength="8"
                  maxlength="20"
                  [(ngModel)]="user.name"
                  #name="ngModel"
                  required
            >
            <div *ngIf="name.errors && (name.dirty || name.touched) class="alert alert-danger">
                <span *ngIf="name.errors.required">Username is required!</span>
                <span *ngIf="name.errors.minlength">Username should be longer than 8 characters!</span>
                <span *ngIf="name.errors.maxlength">Username should be no longer than 20 characters!</span>
            </div>
          </div>
        </div>
        <div class="form-group text-center">
          <button type="submit" name="button" class="btn btn-primary" [disabled]="!userForm.valid">Submit</button>
        </div>
      </form>
    </div>
  </div>
</div>
 // user/user.ts
export class User {
    name: string;

    constructor(name: string) {
        this.name = name;
    }
}
// ./form-demo/form-demo.component.ts
import { Component } from '@angular/core';
import { User } from '../user/user';

@Component({
  selector: 'app-form-demo',
  templateUrl: './form-demo.component.html',
  styleUrls: ['./form-demo.component.scss']
})
export class FormDemoComponent {

  user = new User('Barry');
  constructor() { }


  onSubmit() {
    this.user = new User('Barry');
    //do something
  }
}

Quite straight-forward, everything is shown on the HTML template and you can also understand the behaviors right from the moment you take a glance at the code. This approach is called Template-driven approach or Template-driven form, in which you arrange form elements in the templates and implicit control models (mostly ng...) to provide form functionalities.

There is, indeed, no denying that the code implemented is readable... at the beginning             </div>
            
            <div class=

0