What is the proper way to perform date validation using the moment library in JavaScript?

I am facing an issue with the departure date validation on my website. I have a textbox called txtDepartureDate where users can choose the date of departure. The requirement is that if the selected date is before today's date, an error message should be displayed. To achieve this, I attempted to utilize the `moment` library in Javascript and also employed the `oninput()` event handler. My logic involves calculating the number of days between today's date and the chosen departure date, and if this number is less than or equal to zero, then the error message displayed by the element lblError. However, I am struggling with getting the validation part to work properly.

Textbox:

<asp:TextBox ID="txtDepartureDate" runat="server" ForeColor="Gray" onfocus="txtOnFocusDeparture(this)" onblur="txtOnBlurDeparture(this)" oninput="oninputDeparture()" AutoPostBack="True">DEPARTURE DATE</asp:TextBox>

Script:

<script type="text/javascript>
                    function oninputDeparture() {
                        var inputDate = moment(document.getElementById('txtDepartureDate').value, 'DD/MM/YYYY');
                        var todayDate = moment().format('DD/MM/YYYY');
                        var lblError = document.getElementById('lblError');
                        var daysDiff = todayDate.diff(inputDate, 'days');
                        if (daysDiff <= 0) {
                            lblError.innerText = "Departure Day should be after today";
                        }
                        else {
                            lblError.innerText = "";
                        }

                    }

                </script>

Answer №1

Follow these steps to achieve it:

const userDate = moment([1990, 0, 01]);
const currentDate = moment().toDate();
userDate.diff(currentDate, 'days')

Make sure to input the date in the specified format shown above.

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

Steps to create a new popup and convert it into a new tab

I would like to customize the way a new window opens by displaying it in a tabbed view rather than a separate popup. I have attempted the following methods: var strWindowFeatures = "location=yes,height=570,width=520,scrollbars=yes,status=yes"; var URL = " ...

Is there a method to preserve the pressed/focused state when moving from one input box to the next?

While creating a form for a client, I encountered a requirement where the input box should change once clicked and retain that change even after it has been filled and the user moves to the next input box. Is there a way to achieve this using only HTML & C ...

Node.js Buffer problem: How to tackle it

Encountering an issue with buffers in Node.js The constant buffer is defined as follows: var commands = { BufferOne : new Buffer([0XCA, 0X11, 0X00, 0X00, 0X60, 0X01, 0X00, 0X01, 0X08, 0X07, 0X6D, 0X00, 0X00, 0X00, 0X00, 0 ...

How does the interaction between Express and Angular for routing in the MEAN Stack function?

Currently, I am utilizing Express static to direct to the public directory. //app.js app.use(express.static( __dirname + '/public')); I am looking for a way to have most of the UI routing done by AngularJS. However, it seems that it only works ...

Transfer your focus to the following control by pressing the Enter key

I came across a project built on Angular 1.x that allows users to move focus to the next control by pressing the Enter key. 'use strict'; app.directive('setTabEnter', function () { var includeTags = ['INPUT', 'SELEC ...

What is causing these dynamic carousels to malfunction in Chrome?

After using Agile Carousel successfully for a while, I am now experiencing issues with it not working properly in Safari and Chrome, although it functions fine on Firefox and Safari for iPad. On this specific page, the carousel stops at the second image, ...

Angular17 is throwing an error, indicating that there is no directive with the exportAs value of 'NgForm'

My form component looks like this: <section class=""> <form #loginForm="NgForm" (submit)="onSubmit(LoginForm)" class="flex flex-col mt-[10%] w-fit h-fit m-auto border-gray-200 border-2 p-5 justify-c ...

Unable to perform a GET request to an API with custom headers

I am attempting to send a GET request to an API, but I am encountering an error: Failed to fetch. What could be causing this issue? const getData = () => { fetch("https://test-docs.stores.kg/api/categories", { method: "GET", he ...

Style the date using moment

All languages had a question like this except for JavaScript. I am trying to determine, based on the variable "day," whether it represents today, tomorrow, or any other day. ...

Encountering an internal server error while submitting a Node.js form: stream is not readable

I've encountered an issue while working on a project that involves form submission (Registration and Login). My server is functioning properly and connected to my MongoDB, everything else is working fine, but when trying to submit the form input, an e ...

Retrieve the most recent record in a MongoDB collection

My goal is to retrieve the last document in a MongoDB collection. In the Mongo shell, I was able to achieve this with the following code: db.collection.find().limit(1).sort({$natural:-1}) This query returns the last object as shown below: { "_id" ...

Javascript's ability to import and export modules is a powerful feature

It's clear that there is a strong interest in breaking down large JavaScript projects into smaller modules for code reuse, as discussed in this question. Research indicates that the import/export feature was specifically designed for this purpose and ...

Muting the unused variable alert in JavaScript

Whenever I run my typescript compiler, it always gives me errors about unused variables. In C programming, I would prevent this using the following method: void foo(int bar) { (void)bar; } Is there a similar workaround in JavaScript? ...

If the size of the window changes, the button's functionality should adjust accordingly

$(document).ready(function(){ if ($(window).width < '700') { $(".fevent").removeAttr('data-toggle data-target aria-expanded aria-controls'); $(".fevent").attr({"data-toggle":"collapse", "data-target":"#bol", "aria-expanded": ...

Surprising Outcomes of Negative Margin in jQuery Animation

Unique Project Summary I am currently working on a website that incorporates a sliding menu feature. I have successfully implemented this functionality, and the display remains consistent during the animation transitions for sliding the menu in and out. T ...

What is the purpose of assigning controller variables to "this" in AngularJS?

Currently, I am analyzing an example in CodeSchool's "Staying Sharp with Angular" course in section 1.5. Here is the code snippet: angular.module('NoteWrangler') .controller('NotesIndexController', function($http) { var contro ...

Explore the boundless possibilities of search functionality by utilizing query strings to

This question may seem lengthy, so I appreciate your patience We have an application running on Express, Mongo, React, and Redux. I've developed middlewares and route handlers to process incoming requests by extracting the query string. Below is the ...

Tips for preventing HTTP-request conflicts in JavaScript/AngularJS

Utilizing a combination of JavaScript and AngularJS, I encountered some challenges with HTTP-request race conditions. To simplify the issue for demonstration purposes: imagine having multiple scope.$watch listeners in place, where some may occasionally tr ...

Utilizing React Material-Table to Trigger a React Component through Table Actions

I have set up a datatable using the code below. <MaterialTable icons={tableIcons} title={title} columns={columns} data={data} actions={[ { icon: () => <Edit />, t ...

Error: Uncaught TypeError - Unable to change value of 'innerHTML' for null object in VueJs

I have been encountering a similar problem to others, but despite trying the solutions provided in previous questions, I am unable to resolve it. In my <template>: <modal name="MyModal" > <span class="myClass" id="visible">visible< ...