Published: December 30 2022

Angular + Reactive Forms - Date Validation Example

Example built with Angular 14.2.12 and Reactive Forms

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

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


Angular Date Validation App Component

The app component contains an example form (FormGroup) with a single string field for date of birth (dob). The field has a required validator and a pattern validator, the pattern validator is passed a regular expression to test that the input field contains a valid date in the format 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.

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({ selector: 'app-root', templateUrl: 'app.component.html' })
export class AppComponent implements OnInit {
    form!: FormGroup;
    submitted = false;

    constructor(private formBuilder: FormBuilder) { }

    ngOnInit() {
        this.form = this.formBuilder.group({
            dob: ['', [
                Validators.required,
                // validates date format yyyy-mm-dd with regular expression
                Validators.pattern(/^\d{4}\-(0[1-9]|1[012])\-(0[1-9]|[12][0-9]|3[01])$/)
            ]]
        });
    }

    // convenience getter for easy access to form fields
    get f() { return this.form.controls; }

    onSubmit() {
        this.submitted = true;

        // stop here if form is invalid
        if (this.form.invalid) {
            return;
        }

        // display form values on success
        alert('SUCCESS!! :-)\n\n' + JSON.stringify(this.form.value, null, 4));
    }

    onReset() {
        this.submitted = false;
        this.form.reset();
    }
}


App Component Template

The app component template contains the html markup for displaying the example date validation form in the browser. The form element uses the [formGroup] directive to bind to the form FormGroup in the app component above.

A specific validation message is displayed for each validator by checking the errors object for the input field (*ngIf="f.dob.errors.required" and *ngIf="f.dob.errors.pattern").

The form binds the form submit event to the onSubmit() 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 submitted property of the app component.

The reset button click event is bound to the onReset() handler in the app component using the Angular event binding (click)="onReset()".

<div class="card m-3">
    <h5 class="card-header">Angular + Reactive Forms - Date Validation</h5>
    <div class="card-body">
        <form [formGroup]="form" (ngSubmit)="onSubmit()">
            <div class="row">
                <div class="col-6 mb-3">
                    <label class="form-label">Date of Birth</label>
                    <input type="date" formControlName="dob" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.dob.errors }" />
                    <div *ngIf="submitted && f.dob.errors" class="invalid-feedback">
                        <div *ngIf="f.dob.errors.required">Date of Birth is required</div>
                        <div *ngIf="f.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-2">Submit</button>
                <button class="btn btn-secondary" type="reset" (click)="onReset()">Reset</button>
            </div>
        </form>
    </div>
</div>

 


Need Some Angular Help?

Search fiverr for freelance Angular 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