Vue and Moment JS facing a challenge with today's date validation

I am developing a VueJS application that includes a form component.

Within this form, there is a field for selecting dates.

My goal is to display an error message if the chosen date is older than today's date.

Essentially, the selected date should either be today's date or a future date.

To accomplish this, I am utilizing Moment JS in my project.

Here is the custom rule defined in my Validator.vue:

const dateIsToday = (value) => {
    var todayDate = moment(new Date()).format("DD-MM-YYYY");
    var selectedDate = value;
    return selectedDate>=todayDate;
};

However, I have noticed that this validation only works if an old date within the current month is selected. For instance, choosing 10-04-2022 triggers the error message.

If a past date from last month or another previous month is selected, like 10-01-2022, the error message does not display.

In my form.vue file, the section relevant to date selection looks like this:

<div class="w-1/2 mr-2">
                        <p class="text-certstyle-titles font-bold text-sm mb-1">Start date</p>
                        <div class="h-12">
                            <cs-date-picker
                                id="startDate"
                                v-model="project.start_date"
                                :default-selection="true"
                                :name="`${identifier}-start_at`">
                            </cs-date-picker>
                            <validator
                                :identifier="`${identifier}-validate-project`"
                                :rules="validations.startDate"
                                :name="`${identifier}-start_at`"
                            />
                        </div>
                    </div>

Under the validations section, I have specified the rules for the start date as follows:

startDate: {
                    required: {
                        message: 'Project Start date is required.'
                    },
                    dateIsToday: {
                        message: 'Date has to be today's date or a future date.'
                    },
                },

Answer №1

When dealing with date comparisons, it's important to utilize moment.js for accurate results. Instead of comparing strings directly, convert them into moment dates:

const checkIfDateIsToday = (date) => {
    let today = moment();
    let selectedDate = moment(date, "DD-MM-YYYY");
    return selectedDate.isSameOrAfter(today);
};

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

Modifying the 'child' node within a JSON object

Exploring the implementation of d3s Collapsible tree using a custom node hierarchy. My dataset structure deviates from the norm, for example: http://jsfiddle.net/Nszmg/2/ var flare = { "Name": "Example", "members": [ { "BName":"Ja", ...

What is the origin of the "has" in the "this.has" syntax?

While going through the Nats-Jetstream documentation, I stumbled upon this interesting code snippet: var createModel = require('jetstream').model; var Shape = createModel('Shape', function() { this.has('x', Number); t ...

Accessing an array of objects within nested objects results in an undefined value

I am facing an issue with my JavaScript object that is retrieved from MySQL. The object has a property which contains an array of other objects, as demonstrated below: parentObject = { ID: "1", Desc: "A description", chi ...

Is there a way for me to dynamically incorporate new elements into this object?

I am working with an object msg.data that contains the following information: { "user_id": 1, "success": "true" } Now, I want to add a name field to this list: { "user_id": 1, "success": "true", "name" : "giri" } I have attempted the following ...

Using Jest to verify whether a specific class instance in JavaScript/Typescript calls a function

Currently, I am running tests on express middlewares using jest. it("should throw 400 error if request.body.id is null", () => { const req = { body: { id: null } } as any; const res = {} as any; const next = jest.fn(); myMiddle ...

Navigate to the initial error with Vue Validate in b-form by scrolling

How can I automatically scroll to the first error when submitting a form that is utilizing Vue Validate for validation within a bootstrap (b-form) form? ...

Is it possible to switch the background-image after a gif has finished loading?

I am currently using a GIF as a background image, but I would like it to show a static image until the GIF is fully loaded and ready to play. After reading several similar discussions, I understand that you can manipulate elements with JavaScript once the ...

Integrate a timepicker feature into a Bootstrap-4 table

I'm attempting to integrate a time picker into an HTML table using the JavaScript libraries bootstrap-4.min.js and moments-with-locales.min.js. Here is a link to my project, which includes an HTML table with an input for the time picker: https://jsfi ...

Tips on how to showcase up to 200 characters from a string

<?php include ($_SERVER['DOCUMENT_ROOT'].'/header.php'); include ($_SERVER['DOCUMENT_ROOT'].'/adtop.php'); if(mysql_num_rows($deals) > 0){ while($row = mysql_fetch_assoc($deals)){ echo '<div id= ...

Utilizing Laravel and Jquery UI for asynchronous communication with the server, passing data from a post request to

I recently constructed a basic Jquery UI slider: $("#sliderNumCh").slider({ range: "min", min: 0, max: 20, step: 1, value: 20, change : function(e, slider){ $('#sliderAppendNumCh'). ...

Using $sce in ng-repeat within Angular configuration parameters

I have been trying to incorporate videos using iframes, but no content is being displayed even with the correct embed link. Strangely, when I manually input the link into the iframe tag, the videos show up as expected. Here is the code snippet where I am f ...

The standalone package for webpack's CLI tool has been introduced as webpack-cli

Currently venturing into the world of React.js, I decided to follow the tutorials provided on tutorialspoint. However, during the implementation phase, I encountered an error message in the console upon executing the 'npm start' command: C:&bsol ...

Inject the type into the dependency container

I am managing multiple databases without relying on ORM tools. Here, I will demonstrate an example using Postgres and MSSQL databases with UserQueries. https://i.sstatic.net/GFs5D.png Within my codebase, I have an interface called IDataBase which is impl ...

How can I create a consistent copy button function for an HTML table that works the same across different browsers like Firefox and Chrome?

I am encountering an issue where copying the second row of an HTML table to paste it in an Excel file works perfectly in Firefox, but not in Chrome. When pasting in Chrome, the cells do not match and only the HTML inside the table cells is retained. I am u ...

What is the best way to assign a variable with the type (x:number)=>{y:number,z:number}?

I am trying to initialize a variable called foo, but my current code is not compiling successfully. let foo: (x: number) => {y:number,z: number} = (x) => {x+1, x+2}; This results in the following error: Left side of comma operator is unused and ha ...

Efficiently manage large datasets with Vue.js using the expand/collapse list AJAX pattern

Within my vuejs application, there is a page where I aim to showcase a list of clients. When a user expands an individual client row, it should reveal a list of proposals specific to that client. Additionally, there is an expand/collapse functionality for ...

There was an error in the search: [parse_exception] The search source could not be parsed. A field name was expected, but instead [

I'm experiencing a query parsing exception while utilizing JavaScript for Elasticsearch configuration found in elastic.js file. Results are obtained when the filtered part is removed. However, upon adding it back, an exception occurs. var client = r ...

Utilize jQuery to dynamically apply Bootstrap classes while scrolling through a webpage

Having an issue with jQuery. Trying to include the fixed-top class (Bootstrap 4) when scrolling, but it's not working as expected. jQuery(document).ready(function($){ var scroll = $(window).scrollTop(); if (scroll >= 500) { $(".robig").a ...

Having trouble with the pitch of your rotating camera in Three.js?

I'm still getting the hang of three.js so please bear with me if this question seems a bit basic. My current challenge involves rotating a camera using the arrow keys. While the left and right (yaw) rotation works as expected, I'm encountering i ...

What steps do I need to take to ensure the progress bar extends all the way to the end of the sn

I am currently facing a challenge where the progress bar line in my message queue does not reach the end of the message before it closes. I have included a brief video showcasing the issue along with the relevant code snippet. Any suggestions or ideas woul ...