Angular validation to ensure future dates are not selected

I am interested in exploring Angular's datepicker functionality and implementing date validation to restrict the selection of future or past dates. For example, if today's date is 17/12/2020, users should only be able to select the current date (17), the previous date (16), or any date beyond 17, but not a date before 17 or the next day (18).

I would like to learn how to implement this feature in Angular.

Here is an example snippet from an HTML file:

<div class="form-group col-md-6">
  <label for="date">Date</label>
  <input type="date" formControlName="date" class="form-control" id="date" placeholder="date">
</div>

And here is a snippet from the add-ticket.component.ts file:

import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { Component, OnInit } from '@angular/core';
import { TicketService } from 'src/app/services/ticket/ticket.service';
import Swal from 'sweetalert2/dist/sweetalert2.js';

@Component({
  selector: 'app-add-ticket',
  templateUrl: './add-ticket.component.html',
  styleUrls: ['./add-ticket.component.scss']
})
export class AddTicketComponent implements OnInit {
  public addTicketForm: FormGroup;

  constructor(
    public ticketService: TicketService,
    public fb: FormBuilder
  ) { }

  ngOnInit() {
    this.ticketService.getTicketsList();
    this.buildForm();
  }

  // Additional methods and properties...
}

Answer №1

To set restrictions on the input date field, consider using both the min and max values. The min field is optional.

<input type="date" formControlName="date" min="2021-06-28" max="2021-07-04" class="form-control" id="date" placeholder="date">

If you want to restrict the date range starting from today

<input type="date" formControlName="date" min="2021-06-28" [max]="today" class="form-control" id="date" placeholder="date">

In TypeScript:

today = new Date().toJSON().split('T')[0]

You have the option to exclude the min field if setting a minimum date is not necessary.

Answer №2

To make this happen, all you need to do is specify the max attribute within the input tag.

<div class="form-group col-md-6">
  <label for="date">Date</label>
  <input type="date" formControlName="date" class="form-control" id="date" placeholder="date" max="2020-12-17">
</div>

If you're working with Angular, you can bind it in the following way:

[max]='(new Date).toISOString().split("T")[0]'

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a hyperlink automatically from text with Angular 4

Summary How do I display a clickable link in the browser from text received in json format? Situation I am developing in Angular 4 and retrieving data from an object inside a json file for a simple blog. The issue is that in the json file I am referencin ...

What is the best method for exporting and importing types in React and Next.js apps?

Is there a way to export and import types from API responses in TypeScript? I have a type called Post that I want to re-use in my project. // pages/users.tsx type Post = { id: number; name: string; username: string; email: string; address: { ...

Switching from using Google Geocoding to integrating the Mapbox Places API within an Angular 2 application

I have been developing a web application that geocodes a point upon clicking on a map. The app was initially built in Angular 2, but I do not have a strong grasp of Angular. Currently, the app uses Google for geocoding and updates the text box automatica ...

Nextjs doesn't render the default JSX for a boolean state on the server side

I am working on a basic nextjs page to display a Post. Everything is functioning smoothly and nextjs is rendering the entire page server side for optimal SEO performance. However, I have decided to introduce an edit mode using a boolean state: const PostPa ...

Encountered an issue while saving a blob in NativeScript: "Unable to convert object to [B at index

I have a Nativescript Angular application that is downloading a PDF from a Rails server in Blob Uint8Array format. When I attempt to save it, I encounter the following error: JS: /data/user/0/com.asset.management/files/result.pdf JS: ERROR Error: Uncaught ...

While attempting to code a pop up search bar with HTML, CSS, and JavaScript, I encountered an issue where an error was displayed on the console

<form action="" class="search-form"> <input type="search" id="search-box" placeholder="search here..."> <label for="search-box" class="fa fa-search" aria-hidden=&q ...

Using TypeScript - Implementing Reduce function with a return type containing optional fields

I am facing challenges in satisfying the TypeScript compiler with my code. I define a type that includes only optional fields, for example: interface UserData { email?: string; phone?: string; //... } and I have a reduction function that transforms ...

Guide on how to refresh a child component in Angular after a function yields a fresh value?

Two main elements are at play here: Parent and Child. parent.ts class Parent { state = 0; ... }; parent.html <child [state]='state'> </child> Whenever the state in Parent is modified, the child component reflects the change ...

Is it possible to initiate the onchange event in Angular programmatically using Typescript?

Despite changing the value of an input tag after returning a value from a dialog box (MatDialogRef), the associated change event fails to trigger. Attempts to use dispatchEvent have been made, but creating the event for triggering is not desired as per fo ...

Data not displaying in material table

I am currently testing out the Angular Material table component, but I'm facing an issue where it's not displaying any data and showing the error: Could not find column with id "id". This is confusing to me because my data does have ...

There was an error in reading the 'nativeElement' property in Angular's waveform library, resulting in a TypeError

This is the code I wrote, but it is showing an error: The waveform should be created, but the function to create the waveform is not working. startRecording() { this.mediaSectionVisible = false; if (!this.isRecording) { this.isRecording = t ...

What is the process for upgrading TypeScript to the latest version?

Is there a way to upgrade TypeScript version for ASP.net MV5 project in Visual Studio 2015? I attempted searching through Nuget but couldn't locate it. There seems to be an issue with the razor intellisense (index.d.ts file) and I'm hoping that ...

I am encountering an issue with my testing.spec.ts file. The error message states that XHRs cannot be made from within a fake async test. The request URL causing the problem is http://xxxxxx

After running a test on my service, I encountered the following error: Issue Encountered: Error: Cannot make XHRs from within a fake async test. Request URL: Test File it('should return reasonable json ssss', inject([ProductService, MockBa ...

Conflicting React types found in pnpm monorepo

In the process of converting an inherited monorepo from yarn+lerna to pnpm workspaces, I am encountering some issues. Specifically, there are mismatching React versions causing errors in typescript. It seems that TypeScript is not recognizing the closest @ ...

Unable to execute two queries in the MariaDB SQL server due to a syntax error when utilizing Angular in conjunction with Sequelize

I encountered an issue while attempting to delete records from two separate tables in my database using a SQL command. The goal was to merge two queries for deletion. defaultAdapter.query('DELETE FROM reasons WHERE name = :name') defaultAdapter. ...

Having difficulties injecting a Service into a TypeScript Controller

I recently started working with TypeScript and I created a controller where I need to inject a service in order to use its methods. However, I am facing an issue where I am unable to access the service functions and encountering an error. Error TypeError ...

Activate the mat-menu within a child component using the parent component

Incorporating angular 6 along with angular-material, I am striving to trigger the matMenu by right-clicking in order to utilize it as a context menu. The present structure of my code is as follows. <span #contextMenuTrigger [matMenuTriggerFor]="context ...

Every time I attempt to use interpolation in Angular 11, the result ends up being displayed as plain text on

I'm a beginner in Angular and I recently attempted my first code following a tutorial. When running this code on a live server using port 5500, I encountered an issue with interpolation. <h1>{{title}}</h1> The result on the webpage displa ...

Encountering continuous loops during the resolution of sinon, hindering the ability to conduct proper unit testing in node

In an attempt to implement unit testing in Nodejs using sinon, I have recently installed the following libraries: 1 npm i mocha [2] npm i chai [3] npm i sinon Below is the code that I am working with: unitTest-app.js var sinon = require('sinon&a ...

At what juncture is the TypeScript compiler commonly used to generate JavaScript code?

Is typescript primarily used as a pre-code deployment tool or run-time tool in its typical applications? If it's a run-time tool, is the compiling done on the client side (which seems unlikely because of the need to send down the compiler) or on the s ...