Published: February 06 2023

Angular + Template-Driven Forms - Date Validation Example

Example built with Angular 14.2.12 and Template-Driven Forms

This is a quick example of how to validate a date input field in Angular with Template-Driven Forms. For a more detailed registration form example that includes a bunch of other fields see Angular 14 - Template-Driven Form Validation Example.

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


App Component Template with Date Validation Rules

The app component template contains all the html markup for displaying the example date validation form in the browser. The form submit event is bound to the onSubmit() method of the app component with the event binding (ngSubmit)="onSubmit(f)". The template variable #f="ngForm" creates a FormGroup instance to provide access to the form data and validation status.

Date field registered with parent form

The date input field is registered with the form using the ngModel directive. In the context of a parent form the directive can be used without data binding ([()]), instead the control is registered using the input name attribute and the form keeps the data in sync.

Validators and directives

Validation is implemented by validator functions that are attached to fields using directives. Both validators on the date field come as part of the Angular framework - required and pattern.

Date input validation

The pattern directive is used with a regular expression (^\d{4}\-(0[1-9]|1[012])\-(0[1-9]|[12][0-9]|3[01])$) to validate the format of the date field (yyyy-mm-dd).

Displayed date is different from value

The regex pattern is different to the format of the displayed date, the displayed date is formatted based on the browser locale of the user, but the actual value of the input is always in the format yyyy-mm-dd. For more info on the html date input element see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/date.

<div class="card m-3">
    <h5 class="card-header text-center">Angular + Template-Driven Forms - Date Validation</h5>
    <div class="card-body">
        <form #f="ngForm" (ngSubmit)="onSubmit(f)" novalidate>
            <div class="row">
                <div class="col-6 mb-3">
                    <label class="form-label">Date of Birth</label>
                    <input type="date" name="dob" ngModel #dob="ngModel" class="form-control" [ngClass]="{ 'is-invalid': f.submitted && dob.invalid }" required pattern="^\d{4}\-(0[1-9]|1[012])\-(0[1-9]|[12][0-9]|3[01])$">
                    <div *ngIf="f.submitted && dob.errors" class="invalid-feedback">
                        <div *ngIf="dob.errors.required">Date of Birth is required</div>
                        <div *ngIf="dob.errors.pattern">Date of Birth must be a valid date in the format YYYY-MM-DD</div>
                    </div>
                </div>
            </div>
            <div class="text-center">
                <button class="btn btn-primary me-1">Submit</button>
                <button class="btn btn-secondary" type="reset">Reset</button>
            </div>
        </form>
    </div>
</div>


Angular App Component

The component doesn't do much when using angular template-driven forms since the form fields and validators are defined in the component template.

The onSubmit() method is called with the NgForm template variable when the form is submitted, it is bound to the form element in the template using Angular event binding syntax ((ngSubmit)="onSubmit(f)"). If valid a simple javascript alert is displayed with the values entered into the form.

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

@Component({ selector: 'app-root', templateUrl: 'app.component.html' })
export class AppComponent {
    onSubmit(f: NgForm) {
        // stop here if form is invalid
        if (f.invalid) {
            return;
        }

        alert('SUCCESS!! :-)\n\n' + JSON.stringify(f.value, null, 4));
    }
}

 


Need Some Angular 14 Help?

Search fiverr for freelance Angular 14 developers.


Follow me for updates

On Twitter or RSS.


When I'm not coding...

Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!


Comments


Supported by