November 10 2018

Angular 7 - Template-Driven Forms Validation Example

Example built with Angular 7.0.1

Other versions available:

This is a quick example of how to setup form validation in Angular 7 using Template-Driven Forms. The example is a simple registration form with pretty standard fields for first name, last name, email, password and confirm password. All fields are required, the email field must be a valid email address and the password field must have a min length of 6. There's also a custom validator and directive called MustMatch which is used to validate that the confirm password and password fields match.

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-7-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-8 offset-md-2">
                <h3>Angular 7 Template-Driven Form Validation</h3>
                <form name="form" (ngSubmit)="f.form.valid && onSubmit()" #f="ngForm" [mustMatch]="['password', 'confirmPassword']" 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">
                        <label for="confirmPassword">Confirm Password</label>
                        <input type="password" class="form-control" name="confirmPassword" [(ngModel)]="model.confirmPassword" #confirmPassword="ngModel" [ngClass]="{ 'is-invalid': f.submitted && confirmPassword.invalid }" required />
                        <div *ngIf="f.submitted && confirmPassword.invalid" class="invalid-feedback">
                            <div *ngIf="confirmPassword.errors.required">Confirm Password is required</div>
                            <div *ngIf="confirmPassword.errors.mustMatch">Passwords must match</div>
                        </div>
                    </div>
                    <div class="form-group">
                        <button class="btn btn-primary">Register</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>


Template-Driven Forms Custom "Must Match" Validator

The custom MustMatch validator is used in this example to validate that both of the password fields - password and confirmPassword - are matching. However it can be used to validate that any pair of fields is matching (e.g. email and confirm email fields).

It works slightly differently than a typical custom validator because I'm setting the error on the second field instead of returning it to be set on the formGroup. I did it this way because I think it makes the template a bit cleaner and more intuitive, the mustMatch validation error is displayed below the confirmPassword field so I think it makes sense that the error is attached the the confirmPassword form control.

import { FormGroup } from '@angular/forms';

// custom validator to check that two fields match
export function MustMatch(controlName: string, matchingControlName: string) {
    return (formGroup: FormGroup) => {
        const control = formGroup.controls[controlName];
        const matchingControl = formGroup.controls[matchingControlName];

        // return null if controls haven't initialised yet
        if (!control || !matchingControl) {
          return null;
        }

        // return null if another validator has already found an error on the matchingControl
        if (matchingControl.errors && !matchingControl.errors.mustMatch) {
            return null;
        }

        // set error on matchingControl if validation fails
        if (control.value !== matchingControl.value) {
            matchingControl.setErrors({ mustMatch: true });
        } else {
            matchingControl.setErrors(null);
        }
    }
}


Template-Driven Forms Custom "Must Match" Directive

The custom [mustMatch] directive wraps the custom MustMatch validator so we can attach it to the form. A custom validator directive is required when using template-driven forms because we don't have direct access to the FormGroup like in reactive forms.

The directive implements the Validator interface and registers itself with the NG_VALIDATORS provider to let angular know that it's a custom validator directive.

It accepts an array with the names of 2 form controls that must match in order for form validation to pass, e.g. [mustMatch]="['field1', 'field2']" will validate that field1 and field2 contain the same value, otherwise a validation error will be set on field2. You can see it's usage in the form tag of the app template above.

import { Directive, Input } from '@angular/core';
import { NG_VALIDATORS, Validator, ValidationErrors, FormGroup } from '@angular/forms';

import { MustMatch } from './must-match.validator';

@Directive({
    selector: '[mustMatch]',
    providers: [{ provide: NG_VALIDATORS, useExisting: MustMatchDirective, multi: true }]
})
export class MustMatchDirective implements Validator {
    @Input('mustMatch') mustMatch: string[] = [];

    validate(formGroup: FormGroup): ValidationErrors {
        return MustMatch(this.mustMatch[0], this.mustMatch[1])(formGroup);
    }
}


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. Also import the custom validation directive { MustMatchDirective } from './_helpers/must-match.directive' and include it in the declarations 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';
import { MustMatchDirective } from './_helpers/must-match.directive'

@NgModule({
  imports: [
    BrowserModule,
    FormsModule
  ],
  declarations: [
    AppComponent,
    MustMatchDirective
  ],
  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