May 11 2018

Angular 6 - Template-Driven Forms Validation Example

This is a quick example of how to setup form validation in Angular 6 using Template-Driven Forms. The example is a simple registration form with pretty standard fields for first name, last name, email and password. All fields are required, plus the email field must be a valid email address and the password field must have a min length of 6.

For the same example built with Reactive Forms check out Angular 6 - Reactive Forms Validation Example.

I've setup the form to validate on submit rather than as soon as each field is changed, this is implemented using the f.submitted property of the #f="ngForm" template variable which is true after the form is submitted for the first time.

Styling of the template-driven forms example is all done with Bootstrap 4 CSS.

Here it is in action: (See on StackBlitz at https://stackblitz.com/edit/angular-6-template-driven-form-validation)


Template-Driven Forms Validation App Component

The app component doesn't need to do much since the form fields and validators are defined in the template when using Angular template-driven forms. The component defines a model object which is bound to the form fields in the template in order to give you access to the data entered into the form from the app component.

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

@Component({
  selector: 'app',
  templateUrl: 'app.component.html'
})

export class AppComponent {
  model: any = {};

  onSubmit() {
    alert('SUCCESS!! :-)\n\n' + JSON.stringify(this.model))
  }
}


Template-Driven Forms Validation App Template

The app component template contains all the html markup for displaying the example registration form in your browser. The form input fields use the [(ngModel)] directive to bind to properties of the model object in the app component. Validation is implemented using the attributes required, minlength and email, the Angular framework contains directives that match these attributes with built-in validator functions.

The form binds the submit event to the onSubmit() event handler in the app component using the Angular event binding (ngSubmit)="onSubmit()". Validation messages are displayed only after the user attempts to submit the form for the first time, this is controlled with the f.submitted property of the #f="ngForm" Angular template variable.

<!-- main app container -->
<div class="jumbotron">
    <div class="container">
        <div class="row">
            <div class="col-md-6 offset-md-3">
                <h3>Angular 6 Template-Driven Form Validation</h3>
                <form name="form" (ngSubmit)="f.form.valid && onSubmit()" #f="ngForm" novalidate>
                    <div class="form-group">
                        <label for="firstName">First Name</label>
                        <input type="text" class="form-control" name="firstName" [(ngModel)]="model.firstName" #firstName="ngModel" [ngClass]="{ 'is-invalid': f.submitted && firstName.invalid }" required />
                        <div *ngIf="f.submitted && firstName.invalid" class="invalid-feedback">
                            <div *ngIf="firstName.errors.required">First Name is required</div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="lastName">Last Name</label>
                        <input type="text" class="form-control" name="lastName" [(ngModel)]="model.lastName" #lastName="ngModel" [ngClass]="{ 'is-invalid': f.submitted && lastName.invalid }" required />
                        <div *ngIf="f.submitted && lastName.invalid" class="invalid-feedback">
                            <div *ngIf="lastName.errors.required">Last Name is required</div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="email">Email</label>
                        <input type="text" class="form-control" name="email" [(ngModel)]="model.email" #email="ngModel" [ngClass]="{ 'is-invalid': f.submitted && email.invalid }" required email />
                        <div *ngIf="f.submitted && email.invalid" class="invalid-feedback">
                            <div *ngIf="email.errors.required">Email is required</div>
                            <div *ngIf="email.errors.email">Email must be a valid email address</div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="password">Password</label>
                        <input type="password" class="form-control" name="password" [(ngModel)]="model.password" #password="ngModel" [ngClass]="{ 'is-invalid': f.submitted && password.invalid }" required minlength="6" />
                        <div *ngIf="f.submitted && password.invalid" class="invalid-feedback">
                            <div *ngIf="password.errors.required">Password is required</div>
                            <div *ngIf="password.errors.minlength">Password must be at least 6 characters</div>
                        </div>
                    </div>
                    <div class="form-group">
                        <button class="btn btn-primary">Register</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>


Template-Driven Forms Validation App Module

There isn't much going on in the app module other than the standard stuff, the main thing you need to remember for using template-driven forms in Angular is to import the FormsModule from '@angular/forms' and include it in the imports array of the @NgModule decorator.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';

@NgModule({
  imports: [
    BrowserModule,
    FormsModule
  ],
  declarations: [
    AppComponent
  ],
  bootstrap: [AppComponent]
})

export class AppModule { }

 

Web Development Sydney

Feel free to contact me if you're looking for a web developer in Sydney, I also provide remote contracting services for clients outside Sydney.

 


Sponsored by