JavaScript Birthday Verification: Regular Expression Pattern

I am currently testing out JavaScript form validation. The information provided is not being sent to any database, it's just for format testing purposes. All the regex checks are functioning correctly apart from birth.

It seems like there may be an issue with the regex check related to birth because when I added another check using a different format, it worked fine. The goal is for users to input their birthday in the mm/dd/yyyy format and receive the appropriate error message if not formatted correctly. Any assistance on this matter would be greatly appreciated!

    if(birth == "") {
        printError("birthErr", "Please enter your birthday");
    } else {
        var regex = '/^((0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.](19|20)?[0-9]{2})*$/';                 
        if(regex.test(birth) === false) {
            printError("birthErr", "Please enter a valid birthday");
        } else {
            printError("birthErr", "");
            birthErr = false;
        }
    }
    

Answer №1

Your code may not accurately validate leap years. Consider using the regex provided below, which can handle date formats such as dd/mm/yyyy, dd-mm-yyyy, or dd.mm.yyyy.

^(?:(?:31(/|-|.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(/|-|.)(?:0?[13-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(/|-|.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(/|-|.)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$

Test this regex pattern here

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

Using Javascript or ES6, you can compare a nested array object with another array of elements and generate a new array based on

I am dealing with a complicated array structure as shown below sectionInfo = [{id: 1, name:'ma'}, {id: 2, name:'na'}, {id: 3, name:'ra'}, {id: 4, name:'ka'}, {id: 5, name:'pa'}]; abc = [{id:'1' ...

Modal obstructing BsDatePicker

<!-- The Server Modal --> <div class="modal" id="serverModal"> <div class="modal-dialog" style="max-width: 80%;overflow-y: initial !important;" > <div class=" ...

Unable to locate the value property of a null object

I'm currently working on creating a Shopping Cart using HTML, CSS, JavaScript, and JQuery. The idea is that when you click "Add to Cart" for the orange item, most of the HTML elements will disappear, leaving only the table displaying the Shopping Cart ...

Create a function that generates an HTML string and returns it to be used in JSX

As a newcomer to JSX/React, I am seeking guidance on removing inline code. I have created a function that returns the value to be displayed in the template/JSX. The function works well except when it needs to return a string along with an element like a Li ...

The HTML must be loaded prior to the execution of my JavaScript function

In the controller, there is a function that sets the true value to a variable. function setShow() { return this.isShow === 'Foo'; } The value of this.isShow is set to 'Foo' Within the template, there is <div ng-if = "vm.setShow( ...

Adjust the value of a variable within a module using Angular JS

Within my module, I have the code below: var mod; mod = angular.module('ajax-interceptor', []); mod.config(function($httpProvider) { $httpProvider.interceptors.push(["$q", function($q, dependency1, dependency2) { return { ...

Call getElementById upon the successful completion of an AJAX request

In the process of constructing a mini quiz, I am utilizing a variable quizScore to store the score. Each question in the quiz is displayed using AJAX. An individual AJAX call captures the ID of the button pressed (for example, on question 2, the button ID ...

Issue with CSS not loading correctly when switching routes in AngularJS using Gulp and Router

I currently have a router set up in my application: var mainmodule.config(function($routeProvider){ $routeProvider.when('/home',{ templateUrl:'src/home/home.html' }; $routeProvider.when('/home/sports',{ ...

AngularJS: Utilizing angular-filter for grouping by two columns

I may come across as a bit confusing, so please allow me to clarify. Note: An operational piece of code (POC) has been included with this post. I have an array of objects with 3 properties: name name team team_rank $scope.players = [ {name: & ...

Tips on Implementing a CSS Variable in a React Component

Is there a way to use content variable with in-line styles in React? I am unsure of how to accomplish this. CSS3 .right::after, button::after { content: var(--content); display: block; position: absolute; white-space: nowrap; padding: 40px 40p ...

Issue with spacing dropdown choices within primary navigation bar

Struggling with my final project for a class as the semester comes to a close. I've received minimal help from my Professor and hit a roadblock. The main navigation on the side is working correctly, but the dropdown options are stacking on top of each ...

Recording Node pathways that begin with the hash symbol #

How can I configure my Node/Express routing to intercept a route like /#/about and send it to /about Is there a way for node to handle routes that start with "/#"? It appears to only cut off at the hash mark. ...

[Vue alert]: There was an issue in the v-on function: "TypeError: Unable to access property 'filter' as it is undefined"

Today marks my first experience with Vuex, and so far, I believe I am making good progress. However, after setting up the store, an error popped up in the console stating [Vue warn]: Error in v-on handler: "TypeError: Cannot read property 'filter&apos ...

Delete the HTML line break

I need some help figuring out how to eliminate the line break in HTML. Essentially, I want to display two "Hello World" lines next to each other instead of stacked on top of each other. <p>Hello World</p> <p>Hello World</p> ...

Display solely the error message contained within the error object when utilizing the fetch API in JavaScript

I am facing an issue in logging the error message to the console while everything else seems to be working fine. Specifically, I am unable to log only the message such as "email exists" when the email already exists in the system. const submitHandler = a ...

What could be causing the misalignment of divs with margins?

I'm facing an issue where I can't seem to get two h2 elements with top margin set and placed inside divs floating left to line up properly. Any help would be appreciated. <html> <head></head> <style> h2{ ...

Code snippets to reduce excess white space on a website using HTML and CSS

On my website, there are multiple tabs, each containing content from an HTML file. When a user clicks on Tab1, boxes with images are displayed. The layout can be seen in the following Code Demo: Code Demo here There seems to be extra space before and afte ...

Struggling to make EJS button functional on the template

I am currently facing an issue with a loop that populates a webpage with multiple items, each containing an image, text, button, and a unique ID associated with it. Although I have written a function to retrieve the ID and plan name when the button is clic ...

I'm currently facing an AttributeError issue, and I'm seeking solutions to resolve it

Currently, I am in the process of developing an eCommerce platform using Django. However, I have encountered an issue when attempting to manipulate the quantity of each product in the cart. The error message displayed is as follows: AttributeError at /orde ...

Acquiring HTML form information in ASP.NET controller

Currently, I have a view that includes an HTML login form and I am working on passing the form values to a controller via post. My goal is to display the user's username using the Content method once the form is submitted. However, I am facing an issu ...