Stop users from inputting dates beyond the current date in Angular 4

Encountering an issue with comparing the date of birth object and today's date object using Moment.js. Even if the entered date is smaller than today's date, it still throws an error.

Below is the HTML code:

<div class="form-group datepicker">
      <label for="dob">Date of Birth*</label>
      <div class="row input-group">
        <input
          ngbDatepicker
          #d="ngbDatepicker"
          #dobF="ngModel"
          class="form-control input-underline input-lg"
          id="dob"
          [(ngModel)]="dateOfBirth"
          placeholder="yyyy-mm-dd"
          name="dp"
          [ngClass]="{
            invalid:
              (dobF.value === null || isString(dobF.value) || (dateOfBirth.year > dobYear || dateOfBirth.month > dobMonth || dateOfBirth.day > dobDay) ) && dobF.touched
          }"
          required
        />
        <div class="input-group-append">
          <button
            class="btn btn-outline-secondary calendar"
            (click)="d.toggle()"
            type="button"
          ></button>
        </div>
      </div>
      <div
        *ngIf="
          (dobF.value === null || isString(dobF.value)  || dateOfBirth.year > dobYear || dateOfBirth.month > dobMonth || dateOfBirth.day > dobDay ) && dobF.touched
        "
        class="error"
      >
        Please enter a valid date of birth.
      </div>
    </div>

And here is the TypeScript file where I defined my date of birth:

 public dateOfBirth: { year: number; month: number; day: number };
 public currentDate = moment().format("YYYY-MM-DD");
 public dobYear: any;
 public dobMonth: any;
 public dobDay: any;

  let obj = this.currentDate.split("-");
let obj2 = obj.map(Number);
this.dobYear = obj2[0];
this.dobMonth = obj2[1];
this.dobDay = obj2[2];

The error occurs due to today's month being 02, causing issues when entering a date like 2012-09-09 because 02<09. Any suggestions on how to resolve this issue would be greatly appreciated. Thank you!

Answer №1

One possible solution is to utilize Date objects instead. By comparing them directly and implementing a custom Validator in a reactive form, you can easily handle checking for valid dates.

Alternatively, if you prefer to stick with your current approach, you will need to verify the year, then the month, and finally the day to ensure correctness. However, this method may result in code that is difficult to read:

(dobF.value === null || isString(dobF.value)  || dateOfBirth.year > dobYear || (dateOfBirth.year == dobYear && dateOfBirth.month > dobMonth) || (dateOfBirth.year == dobYear && dateOfBirth.month == dobMonth && dateOfBirth.day > dobDay)) && dobF.touched

Answer №2

To prevent users from entering future dates, simply use the [max] attribute. You don't have to create this validation method from scratch.

Check out more details here: https://material.angular.io/components/datepicker/api

Here's how you can implement it in your HTML:

<input
  ngbDatepicker **[max]="maxDate"** ... 

And in your controller:

public maxDate = new Date()

Answer №3

Here is my recommendation for you.

  1. To enhance user experience with the date picker, consider making the input field readonly.
  2. Add [maxDate]="maxDate" to set the maximum selectable date as today's date using the code snippet below:

     import * as moment from "moment";
    
     **Declaration:-** 
    
     maxDate: {};
      today = new Date();
    
    constructor(){
        this.maxDate = {
          year: parseInt(moment(this.today).format('YYYY')),
          month: parseInt(moment(this.today).format('MM')),
          day: parseInt(moment(this.today).format('DD')),
        }
    }
    

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

Ways to transfer information from a parent component to a child component in Angular 5 without the need for *ngFor

Currently, I am utilizing *ngFor to iterate through a selector and passing data to the child component. Let's take a look at the code snippet below: <app-piegraph *ngFor="let studentData of studentData" [studentData]="studentData"></app-pieg ...

What is the best way to combine JavaScript objects with identical values?

We have a task to compare each input key with others to find any common values. If there are common values, we need to concatenate them together and display the pairs. If no common values are found, then an empty array should be displayed as output. inpu ...

Form for creating and updating users with a variety of input options, powered by Angular 2+

As I work on creating a form, I encounter the need to distinguish between two scenarios. If the user selects 'create a user', the password inputs should be displayed. On the other hand, if the user chooses to edit a user, then the password inputs ...

Using ng-repeat and selectize in AngularJS to populate a multi-select drop-down with values and set selected values

In this instance, I was able to achieve pure HTML select multiple functionality by using this example (JS Bin of pure html select tag). However, instead of sticking to just the pure HTML approach, I opted to use the Selectize plugin. The confusion arose w ...

What is the best way to retrieve the errors recorded property from a customized input component that has been validated with vee-validate?

I am currently exploring the use of VeeValidate within a custom input component. In my attempts, I have experimented with using $emit on both @input and @blur events. However, I have encountered an issue where validation takes place in the next tick, caus ...

"Adjusting the width of columns in a Datatable

I have arranged a data table with multiple rows and columns, and I am seeking guidance on how to increase the width of the "Tel. 1, Tel. 2, and Fecha" columns to ensure that the text appears on a single line. I've attempted adjusting the s width and t ...

Determine the Height of the Container once the Font File has Finished Loading

When styling a website with a unique font using @font-face, the browser must download the font file before it can display the text correctly, similar to how it downloads CSS and JavaScript files. This poses an issue in Chrome (v16.0.912.63) and Safari (v5 ...

What is hindering me from fetching the information stored in my json file?

Currently, I am delving into learning AngularJS by working on a simple webpage for a company. This page will showcase products that are fetched from a json file. Following a tutorial from the AngularJS website, which covers the exact task I aim to achieve, ...

creating a function within an object that allows for chaining

My goal is to create a chainable object, but I am struggling to implement this in a function. This is the functionality I desire: $donate.ga('testing').go(value); The code for my object currently appears as follows: var $donate = { ga: fu ...

How can I modify the fill color of a Cell when hovering over a Bar Chart in Recharts?

I have been rendering the chart in the following manner: <BarChart width={868} height={40} data={data} margin={{top:0, bottom: 10, left:0, right:0}} barSize={5}> <Tooltip labelStyle={{ textAlign: &apo ...

jQuery registers the enter event, but does not proceed to trigger the enter action

Hey there, I've been experimenting with jQuery to capture the enter event. Something peculiar is happening though - after pressing enter in the text area, an alert pops up but the text gets entered only after that. Despite trying various solutions, I ...

Why do I keep receiving a <prototype> object for each API request?

Currently, I am utilizing JSONPlaceholder in conjunction with Angular as part of my learning process. While I have been following the documentation meticulously and obtaining the correct output, there seems to be an additional element accompanying each obj ...

Guide on implementing a .catch method in Firebase's onSnapshot function

I have recently developed an Ionic Firebase chat application. I seem to be encountering an issue with setting up a query snapshot when initializing the message page. Here is the code snippet that I am using: ngOnInit() { this.messageService.getA ...

Styling of checkboxes in jQuery Mobile is missing after an AJAX request

I am currently working on implementing an ajax call to retrieve a list of items from a json array and display them as checkboxes. While the items are loading correctly, they lack the jquery mobile styling. $(document).ready(function(){ ...

Having difficulty navigating to a different page in Angular 4

I'm currently attempting to transition from a home page (localhost.com) to another page (localhost.com/listing). Although the app compiles correctly, I encounter an issue where nothing changes when I try to navigate to the new page. My approach has m ...

What is the best way to position a tooltip near an element for optimal visibility?

One div is located on the page as follows: <div id="tip"> Text for tip goes here... </div> And another one can be found below: <div class="element"> Text for element goes here... </div> There is also a piece of JavaScript ...

The best practices for utilizing getStaticProps with Firebase

I am completely new to Next.js and am struggling to make the getStaticProps function work properly. import firebase from '../firebase' export default function Home({ posts }) { return ( <div> <h1>All Posts</h1> ...

Looping through an object with AngularJS's ng-repeat

Upon receiving an object as the scope, which has the following structure: The controller function is defined as follows: module.controller('ActiveController', ['$scope','$http', function($scope, $http) { $h ...

Error message "Cannot find children property on type IntrinsicAttributes & RefAttributes<unknown>" occurring in a React component due to a Typescript issue

Issue: The specified type '{ children: string; severity: string; sx: { width: string; }; }' is not compatible with the type 'IntrinsicAttributes & RefAttributes'. The property 'children' is missing in the type 'Intri ...

Keep verifying the boolean value repeatedly

I've been working on implementing infinite scroll functionality for my card elements. Within my data.service file, I have a variable called reload that is utilized to determine whether more data needs to be loaded. This variable is set to true when th ...