Having trouble with javascript regex for date validation?

I am facing an issue with using JavaScript regex to validate date inputs. It is identifying valid dates as invalid, and I'm not sure what the problem is:

/^([0-9]d{2})+(\.|-|\/)+([0-9]d{2})+(\.|-|\/)+([0-9]d{4})+$/

The date formats that should be accepted are:

23/04/2001

23-04-2001

23.04.2001

Initially, I tried this regex pattern but it was accepting dates with extra characters at the end like 23/04/2001jhsdgf:

/\d{2}(\.|-|\/)\d{2}(\.|-|\/)\d{4}/;

Answer №1

To fix your original regex, simply include the ^ and $ from your updated version. Problem solved.

UPDATE: However, it might be better to replace the messy (\.|-|\/) with [.\/-].

UPDATE 2: Another option is to use ([.\/-]) for the first one and then reference it with \1 for the second one, ensuring both separators are the same.

Answer №2

To verify if a date is correctly formatted, you can utilize a regular expression like the following:

/^(\d{1,2})([-\.\/])(\d{1,2})\2(\d{4})$/
  • ^ indicates the start of the string, and $ represents the end
  • \d{1,2} matches either 1 or 2 digits
  • \d{4} corresponds to exactly 4 digits
  • \2 references the separator captured in the second group (- . /)

If a match is found, you can extract the day, month, and year values to construct a new date for comparison. Below is a function that accomplishes this:

function checkDate(dateText) {
    var match = dateText.match(/^(\d{1,2})([-\.\/])(\d{1,2})\2(\d{4})$/);
    // "31.04.2012" -> ["31.04.2012", "31", ".", "04", "2012"]
    if (match === null) {
        return false;
    }
    var date = new Date(+match[4], +match[3] - 1, +match[1]);
    return date.getFullYear() == +match[4] && 
      date.getMonth() == +match[3] - 1 && 
      date.getDate() == +match[1];
}
checkDate("30.04.2013"); // true
checkDate("31-04-2013"); // false (April has 30 days)
  • The use of + converts strings to numbers (e.g., +"01" becomes 1)
  • Months are indexed from 0 (0 = January, 1 = February, etc.)
  • This example assumes the date format as dd-mm-yyyy

The Date object adjusts erroneous dates automatically. For instance, attempting to create 31-4-2013 results in 1-05-2013; the above function validates the resulting date against the input parameters.

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

Is there a way to incorporate CSS into an element utilizing jQuery when only a class is available for identification, and when the time in the innerHTML is within a 5-minute range from the current time?

I have some HTML code that I need help with: <td class="mw-enhanced-rc">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;18:10&nbsp;</td> My goal is to use JavaScript to make the time bold. $('td[class^="mw-enhanced-rc"]').eac ...

Interact with visible elements by automating mouse clicks with puppeteer

When attempting to click on various elements within a page, my goal is to do so only if they are visible. While achieving this in selenium with the is_displayed method was simple, I have struggled to find a similar approach in puppeteer. I attempted to imp ...

JavaScript Grouping Arrays

I am working with an array and need to filter it by both Country and Service. So far, I have successfully filtered the array by Country. Now, I want to achieve the same filtering process based on the Service as well. Here is a snippet of the array: [ ...

I'm looking to create a unique combination of a line and bar chart. Any advice on how to

When I stretch my Scale like this determineDataLimits: function () { var min = Math.min.apply(null, this.chart.data.datasets[0].data) console.log(this) console.log(defaultConfigObject) Chart.options.scales.rightSide.ticks.min = function ...

Configure webpack to source the JavaScript file locally instead of fetching it through HTTP

Using webpack.config.js to fetch remote js for Module Federation. plugins: [ new ModuleFederationPlugin({ remotes: { 'mfe1': "mfe1@http://xxxxxxxxxx.com/remoteEntry.js" } }) ], Is it possible to incorporate a local JS ...

What could be the reason my this.setState is not properly updating the array?

Is there something I'm overlooking? I've implemented the es6 style to add to an empty array in this.state, but nothing is being pushed to state. I should have a total of two elements inside the array, however, after console.logging, nothing is a ...

Communicating between PHP chat client and server

Currently, I am developing a basic PHP web chat application that interacts with a MySQL database. The communication is facilitated through AJAX requests - when a user posts a message, it gets saved in the database. function sendData(){ var textData = $(& ...

The image from the local source displays correctly in the initial component without any issues, but it does not appear in its corresponding detail component

My blog has a component for displaying posts and another component for showing the details of a single post as seen below. A key point to note is that while the blog component can load and display images, the blog details component cannot. Why is this? A ...

JQuery ID Media Queries: Enhancing responsive design with targeted

Is it possible to integrate a media query into the selection of an ID using JQuery? For example: $('#idname') $('@media (max-width: 767px) { #idname }') In essence, can you target the #idname with that specified media query in JQuery ...

Failed to decipher an ID token from firebase

I'm feeling extremely frustrated and in need of assistance. My goal is to authenticate a user using Google authentication so they can log in or sign up. Everything worked perfectly during development on localhost, but once I hosted my app, it stopped ...

Can Cell be rendered into a targeted element?

Can a Cell from CellJS be rendered into a specific HTML element? For example, including a Cell alongside some static HTML that is not managed by cell. Or having two separate Cell apps on a single page. <!DOCTYPE html> <html> <header> ...

Leveraging Google Cloud Functions with Next.js (Client-Side Rendering)

Having trouble incorporating firebase cloud functions into my Next.js project, encountering an unfamiliar error. firebase-config.js const firebaseConfig = { apiKey: '~~~', authDomain: '~~', projectId: '~~~', storageBu ...

Which is better for handling events - jQuery delegation or function method?

Which approach is quicker and has broader browser support? 1. Utilizing a JavaScript function such as: function updateText(newtext) { $('div#id').text(newtext); } and incorporating it into an element's onclick event: <button onc ...

Vue: Opening all GmapInfoWindows simultaneously upon clicking one

I am working on a platform where users can report crimes or incidents by placing markers on a map. These markers with all the reported incidents are then displayed on another map. Each marker has an info window that provides details about the incident and ...

Implement a transition effect for when elements change size using the `.resizable().css` method

I attempted to incorporate a deceleration effect when resizing an element back to its original size using the resizable method. The slowdown effect should only trigger during the click event (when the "Click-me" button is pressed), not while manipulating ...

Is it considered beneficial to use Observable as a static class member?

Lately, I have been diving into a new Angular project and noticed that the common way to share state between unrelated components is by using rxjs Subject/BehaviorSubject as static members within the class. For instance: export class AbcService { privat ...

Guide on making a persistent sidebar using CSS and JavaScript

I'm in the process of developing a website that features a main content area and a sidebar, similar to what you see on Stack Overflow. The challenge I am facing is figuring out how to make the sidebar remain visible as a user scrolls down the page. T ...

Vue.js error: Reaching maximum call stack size due to failed data passing from parent to child component

I'm having trouble passing data from a parent component to a child component. I tried using props and returning data, but with no success. The parent component is a panel component that contains the data, while the child component is a panelBody. Thi ...

Why does the Angular page not load on the first visit, but loads successfully on subsequent visits and opens without any issues?

I am currently in the process of converting a template to Angular that utilizes HTML, CSS, Bootstrap, JavaScript, and other similar technologies. Within the template, there is a loader function with a GIF animation embedded within it. Interestingly, upon ...

Utilizing Vue: Attaching click event to dynamically added elements

I am working on a Vue application that retrieves HTML content from an API. This HTML contains blocks with the class <div class="play-video">...</div> Using axios to call the API and a promise, I insert the content into the DOM like this: < ...