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

What is the process for combining and compressing an Angular 2 application?

I am currently trying to concatenate and minify an angular2 application. My approach so far involved concatenating all my *.js files (boot.js, application.js then all components) into one file and injecting it into my index.html. I also removed the <s ...

Encountering Issues with Importing vue-router in Vue.js 3 - What Could be the Problem?

Here are the files I am working with: router.js import VueRouter from 'vue-router' export const router = VueRouter({ routes: [ { ... } ] }) main.js import { createApp } from 'vue' import App from './App.vue ...

Transfer a term to a different division - JavaScript Object Model

I am trying to achieve a specific task where I need to move one term under another in SharePoint. However, despite my efforts using JSOM and SharePoint 2013, I have not been able to find a direct method for moving terms. The code snippet I have used below ...

Exploring the World of Angular JS Services

Following the recommended practices, I am working on encapsulating my global functions into reusable factory services. In the provided code snippet, my objective is to execute a function that takes the string value of "Qprogress" from my JSON data, perform ...

Is there a way to update page content without having to refresh the entire page?

My goal is to refresh specific content on a page without having to reload the entire page using JavaScript or jQuery. Since my project is built in PHP and JavaScript, I encountered this issue. Note : I want the page content to refresh when a user performs ...

React Redux causing React Router to display empty pages

In my App.js, the following code is present: const Index = asyncRoute(() => import('~/pages/index')) const Register = asyncRoute(() => import('~/pages/register')) const AddDesign = asyncRoute(() => import('~/pages/add-des ...

Send form data when opening a fresh page with Javascript

In the WordPress build for our company, there is a need to transfer data when previewing a page. To streamline this process, my boss wants to override the default functionality of the preview button by opening a new tab and passing the necessary data throu ...

What steps should I take to create a collapsible Bootstrap navbar?

I'm attempting to recreate the scrolling functionality seen here: It seems like they might be using a customized Bootstrap Navbar, so I've taken one from here: and tailored it to my needs. How can I achieve the effect where the navigation bar ...

When attempting to use JQuery autocomplete, the loading process continues indefinitely without successfully triggering the intended function

Currently, I am utilizing JQuery autocomplete to invoke a PHP function via AJAX. Below is the code snippet I am working with: $("#client").autocomplete("get_course_list.php", { width: 260, matchContains: true, selectFirst: false }); Upon execution, ...

Best practice for integrating Typescript into an established ASP.NET 4 Webforms project

Currently, I am working on an older asp.net 4.0 Webforms project using Visual Studio 2015. My goal is to transition from using Javascript to TypeScript for certain client side code tasks. While I have experience using TypeScript in projects outside of Vis ...

When the button is clicked, a modal will pop up

Looking for help in incorporating JavaScript to create a responsive modal that pops up with lyrics when a button is pressed in a table. Any assistance would be greatly appreciated. Note: Only the code for the table has been provided. Let me know if you&ap ...

Guide to Aligning Divs at the Center in Bootstrap 4

I've been attempting to center the div on the page using Bootstrap 4, however, it's not cooperating. I've tried using the margin:0 auto; float:none property as well as the d-block mx-auto class, but neither are working. Below is my HTML code ...

Encountering the error message "Function.prototype.bind.apply(...) cannot be invoked as a constructor

I'm attempting to implement Controller Inheritance in AngularJS (1.6.9), but encountering an error in the console: Function.prototype.bind.apply(...) is not a constructor. Here's the snippet from the HTML file: <!-- Controller Inheritance --& ...

Exploring front-end AJAX functionality within a WordPress plugin

As a newcomer to WordPress development, I have been working on writing an AJAX request within a WordPress plugin. To test this functionality, I initially sent the request to an external non-WP server where it worked without any issues. Following the guidel ...

What is the method for a HTML button to trigger the execution of a Selenium (Java) code located in a remote location through a

I need to run a Selenium Code written in Java from a NAS (Network Attached Storage) or another connected machine. My goal is to create a web page with a button that, when clicked, triggers the execution of the Selenium script located on the connected mac ...

Chrome's display of HTML5 form validation bubble is not aligned correctly

Can anyone shed some light on why the Form Validation Bubble is showing up with a big offset in Google Chrome when trying to validate a form inside a jquery UI dialog? It seems to work fine when the javascript call creating the dialog is removed. Just want ...

Adding a loading event listener to an object in JavaScript: A step-by-step guide

I'm currently deep into developing a game using sprites in JavaScript. I've been trying to incorporate an event listener that verifies whether the sprite images have loaded before beginning the game. Employing object-oriented programming, I' ...

Is there a way to broadcast a message to all the Discord servers where my bot is currently active using v14 of discord.js?

Can someone assist me in creating code that allows me to send a message to all servers at my discretion? I have not found any resources on this topic for discord.py or the newer versions of discord.js ...

Mastering form reset functionality using jquery

When attempting to register, an error is generated if any field is left blank in the form (from PHP). The input fields that have been filled out are retained using Smarty: {if isset($smarty.post.registratie.naam)} value="{$smarty.post.registratie.naam}"{el ...

Renaming properties in an AngularJS model

After receiving the data in a structured format, my task is to present it on a graph using radio buttons. Each radio button should display the corresponding category name, but I actually need each button to show a custom label instead of the original categ ...