Struggling with date validation as a new MomentJS user

Looking to validate a date in string format using moment JS, I am encountering an issue.

Using the dd/mm/yy format in pCalendar in ngPrime, I store the date value in stDate.

Here is the code I have written:

var stDate = '02/02/2021';
var stDateMoment = moment(stDate, 'dd/mm/yy');

I'm puzzled as to why the expression

stDateMoment.isValid()

is returning a false value.

Any insights or suggestions on what might be causing this?

Appreciate your help!

Answer №1

You are on the verge of success. Remember that the format tokens are sensitive to case, meaning you should not use lowercase dd, mm, or yy.

const startDate = '02/02/2021';
const startDateMoment = moment(startDate, 'DD/MM/YYYY');

console.log(
  startDateMoment.isValid() 
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

To learn more about this, please refer to the momentjs string format documentation.


The documentation also explains that two Ys represent two-digit years, while four Ys stand for four-digit years.

Answer №2

To resolve the problem, you can create a Date Object for the formatted date provided

var newDate = new Date("02/02/2021");
var newDateMoment = moment(newDate,"DD/MM/YY");
const checkValidity = newDateMoment.isValid(); // returns true

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 retrieve keys from the json object below

Working on integrating handsontable with a php backend, I'm attempting to dynamically generate table column headers. This involves creating an array of column names that will be used in handsontable like so: colHeaders: ['ID', 'First&a ...

Even in report-only mode, Content Security Policy effectively blocks the execution of inline scripts

Currently, I have implemented a Content Security Policy (CSP) in 'Content-Security-Policy-Report-Only' mode with a specified report-uri. There is an inline JavaScript code running on the page that the CSP restricts. My initial expectation was tha ...

What is the method for adding a tag within a specific div ID in ExtJS?

I am looking to insert a new tag within existing tags using extjs, based on the div id 'task123', and also trigger an alert message accordingly. Below is the HTML code snippet: <div id="task123"> <div class="msg" id="sample"> ...

Using jQuery to fetch and read the source code of a specified URL

I'm facing an issue with extracting the source code of a website URL into a variable. Here is my current approach: <script type="text/javascript"> debugger; $(documnet).ready(function () { var timer = $.ajax({ type: ...

Is there a way to assign the scroll event context to `document.body` instead of `window`?

Discovery As I delved into the intricacies of web development, I stumbled upon a curious observation. In a particular MDN page, I noticed that the left and right sidebars had their scrollbars contained within themselves. However, the content block's ...

AngularJS input range is written inside the bubble that crosses over the screen

Is there a way to write inside the bubble of the range slider? I have adjusted the design of the range slider and now I simply want to display the number inside the bubble: Please see image for reference I aim to display the number inside a circle. What ...

JSON objects not loading properly in Bootstrap table

I am facing an issue where my ajax script successfully sends JSON objects to the browser, but the table fails to load the JSON object. Here is my Ajax script: $.ajax({ type : "POST", url : "getLabels.jsp", data : "mail ...

Assign an AJAX call to retrieve data from a MySQL table and store it in a

In my database, I have a table that includes fields for 'user_name' and 'user_round'. My goal is to set the 'user_round' field to match the value of a JavaScript variable called 'Level'. However, when I run my code, ...

Deactivated the UpdateProgress functionality for the entire webpage

After exploring various options, I came across this solution: Is there a way to disable UpdateProgress for certain async postbacks? However, implementing this solution seems to prevent my controls from loading altogether! In my master page, there is an U ...

Expanding Drop-Down Feature in CodeIgniter: How to Create Nested Dropdown Menus

I'm working on a dropdown menu that is populated with items using a foreach statement. When an item is selected, I need another dropdown menu to appear where specific items can be specified. First Dropdown - Categories (Completed) When a Category is ...

The changes made to the code in node.js are not being accurately reflected in the

Previously, I had a route set up with a post request named /brands/createBrand. No matter how many adjustments I make to it, I am unable to see any output. I attempted hosting the entire project on render.com, but it yielded no changes. Here are the steps ...

Tell webpack to exclude a specific import

Currently, I am in the process of developing a desktop application using ElectronJS and ReactJS. To bundle the renderer process that utilizes JSX, I have opted to use webpack. An issue arises when attempting to import anything from electron into the rend ...

UI thread was blocked due to withProgress being invoked from an external library function

Currently enhancing an extension that is almost finished, but facing a challenge in adding visual cues for lengthy operations. Initially suspected a missing async/await in the code, but struggling to identify the cause. The progress indicator isn't di ...

What is the best way to utilize JQuery AJAX to send XML data for a delete request?

I am having trouble sending XML type data to the backend using jQuery and AJAX as a DELETE request. When I do this, I receive an empty array from the backend's request body. How can I properly send the ID? Below is the code I am using: function delet ...

Ensured static element-UI table dimensions even with modifications to columns

Creating an Element-UI table and using v-if to control column show/hide has been working perfectly, except for one small issue. The table seems to automatically change size when columns are shown/hidden, even though I have already set fixed width and heig ...

Utilize state objects and child components by accessing sub-values within the object

I have a Dropzone component where multiple uploads can happen simultaneously and I want to display the progress of each upload. Within my Dropzone component, there is a state array called uploads: const [uploads, setUploads] = useState([]) Each element i ...

Explore various locations and conceal different divs by clicking

Can someone help me figure out how to hide the placeholders when the focus changes in a form? Here is the code snippet that illustrates my problem. Your assistance is greatly appreciated, João var inputs = Array.prototype.slice.call(document.querySele ...

PHP live data updating: stay current with real-time data updates

I have a functional API that is currently static, but I want it to update periodically and display live data in my HTML code. I'm not sure where to begin. Should I start with Javascript or Ajax? Any guidance would be greatly appreciated. This is my ...

How to refresh component after clearing dates in Vuetify datepicker

Currently, I am working with a datepicker in Vuetify JS and I need to find a way to clear the dates and refresh the component. In addition, there is a v-data table that is filtered based on the dates range array. I am exploring options to either add a &ap ...

NextJS throwing an error: Unable to access property 'json' as it is undefined

In my NextJS environment, I have a code file in the pages folder that fetches data from an external API Rest. The code is functional as the console.log(response); line displays the JSON API response in the console. However, I encountered an error in the br ...