What is the process for validating dates using JavaScript?

I'm currently working on a birthday validation form using JavaScript and I'm facing some issues. For instance, the date 40/40/2012 should be considered invalid but no alert is being triggered.

Here is the JavaScript code:

function validateBirthday(form_element) {

    var birthday = form_element.birthday.value;
    if ( !/\d{2}\/\d{2}\/\d{4}/.test(form_element.birthday.value) )
    {
        alert("This field is required. Please enter a valid date in the format mm/dd/yyyy!");
        return false;
    }
    return true;
}

And here is the HTML form code:

<form onsubmit="return validateBirthday(this)">
    Birthday:<input type="text" name="birthday" /><br />
     <input type="submit" value="Submit" />
</form>

Answer №1

My preferred activity involves the following:

let birthday = form_element.birthday.value;
let match = /^(\d\d)\/(\d\d)\/(\d\d\d\d)$/.exec(birthday);
if (!match || match.length < 4) return false;

let d = new Date(match[3] - 0, (match[2] - 0) - 1, match[1] - 0);
if (d.getFullYear() != match[3] || d.getMonth() + 1 != match[2] || d.getDate() != match[1])
  return false;

return true;

Creating a date using valid year/month/day values and then verifying those on the Date object should yield identical results. Any discrepancies would indicate that the Date object adjusted incorrect values to fit within a valid date representation.

edit — apologies as my code is set up for day/month/year format; if you require month/day/year format, interchange match[2] and match[1] in the provided code snippet.

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

Converting a Javascript object to JSON format only once using AngularJS

Is it possible to convert a JavaScript object to JSON using angular.toJson only once in my code? Here is an example: $scope.task.tags = [{"id":22,"tag":"printer","created_at":"2016-03-15" }]; $scope.create = function(task) { tmp.tags = angular.toJson( ...

Are specific names set aside for JQuery Selectors?

One time, I made a mistake with my selector: $("#cut") Unfortunately, this was not pulling the object correctly even though I had defined an object with that id in the HTML. After changing the object's id (and updating the selector), everything work ...

Upon initiating a refresh, the current user object from firebase Auth is found to be

Below is the code snippet from my profile page that works perfectly fine when I redirect from the login method of AuthService: const user = firebase.auth().currentUser; if (user != null) { this.name = user.displayName; this.uid = user.uid; } e ...

Display JSON data in AngularJS and show the corresponding data on the right side when clicked

I'm brand new to using AngularJS and I've been struggling with this issue. Take a look at the code snippet below to see what I mean. The titles are shown on the left, and when you click on one, I want the corresponding body to display on the righ ...

Unable to submit /api/sentiment

I'm currently troubleshooting the /api/sentiment endpoint in postman and encountering a "cannot POST" error. I have confirmed that the routes are correct and the server is actively listening on port 8080. Interestingly, all other endpoints function wi ...

What could be causing the error in sending JSON data from JavaScript to Flask?

Check out this cool javascript code snippet I wrote: <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script type=text/javascript> $(function() { $.ajax({ type: 'PO ...

Highlighting text within ReactJS using Rasa NLU entities

Currently, I am working on a React application that retrieves data from the Rasa HTTP API and displays it. My goal is to tag the entities in a sentence. The code functions correctly for single-word entities but encounters issues with two-word entities (onl ...

Enhancing visual appearance with customized look control through the use of setAttribute

I have developed a unique custom look-controls feature and I am trying to integrate it into the scene using 'setAttribute(componentName, data)', but I'm unsure about what parameters to include. Any suggestions? Here is my approach: const s ...

Implementing slideDown() functionality to bootstrap 4 card-body with jQuery: A step-by-step guide

Here is the unique HTML code I created for the card section: <div class="row"> <% products.forEach(function(product){ %> <div class="col-lg-3 col-md-4"> <div class="card mb-4 shadow "> &l ...

The typing library for Angular does not properly identify the JQueryStatic object

Encountered an issue with the Angular declaration file: Error TS2304: Cannot locate identifier 'JQueryStatic'. The typings for jQuery are installed and properly declare JQueryStatic as an interface. Looking for solutions to resolve this error. ...

Encounter issue when using GAS withSuccessHandler function

I've developed a Google Sheets add-on that utilizes a modal dialog for the user interface. I encountered an issue with the success handler not running as expected, so I created a basic test interface to troubleshoot the problem. After the server-side ...

Utilize JavaScript and HTML to show error messages based on whether the user is deactivated or if the input is invalid

I need to show different error messages under the 'Email Address' input if the user is disabled and under the 'Password' input if the user is invalid. In my debugging process, I discovered that a user being disabled results in a "Status ...

What is the best way to integrate an AJAX callback into the stop condition of a `do while` loop?

Take a look at the code snippet below: let count = 0; do { $.ajax({ type: "POST", url: someurl, dataType: 'xml', data: xmlString, success: function(xml) { count++; } } while(co ...

Diagnosing Issues with Yii2's $(document).ready Function

AppAsset: public $js = [ 'plugins/jquery/jquery.min.js', 'plugins/jquery/jquery-migrate.min.js', 'app.js', ]; When I write this in a view file: $script = <<< JS jQuery(document).ready(function( ...

Creating a unique styleset in styled-jsx using custom ruleset generation

TL;DR What's the best way to insert a variable containing CSS rules into styled-jsx (using styled-jsx-plugin-sass)? In my JSX style, I have the following: // src/pages/index.tsx ... <style jsx> {` .test { height: 100vh; width ...

Postman grants me the cookie, yet Chrome doesn't seem to deliver it

As I attempt to set a cookie named auth, containing the user's ID signed with JWT, I am puzzled by not seeing the auth cookie in Chrome when visiting http://localhost:5000/. Instead, I only observe these two cookies; https://i.sstatic.net/p0Foo.p ...

Enable users to modify the URL in the window.open() function

In the code snippet below, a new window opens when a user clicks on a button: $('.loginButton').click(function () { var strString = $("#medlineSearch").val() var strSearch = "http://google.com&query="; var url = strSearch + strSt ...

How do I utilize the file handler to execute the flush method within the Deno log module using Typescript?

I'm having trouble accessing the fileHandler object from my logger in order to flush the buffer to the file. This is the program I am working with: import * as log from "https://deno.land/<a href="/cdn-cgi/l/email-protection" class="__cf_emai ...

What is the most effective method to patiently anticipate a specific duration for a function's output?

I am faced with a situation where I have two functions at hand. One function performs complex logic, while the other wraps this function to provide either the result of computation or an error message after a specified amount of time t. Consider the follo ...

The art of masonry is not effective

I'm having trouble getting the Masonry cascading grid layout library to work in my code. Stylesheet: .post { background: #FFF; padding: 10px; border-bottom: 3px solid #e6e6e6; width: 30.7%; margin: 10px; } Source code: <div ...