Datetime Format Regex (MM/dd/yyyy) Javascript

I want to validate the date format on every keypress/keyup that the user's typed.

I've researched for what i'm trying to achieve. And I've found the solution here: 

(i was referring to @bobble bubble's answered)

but the format was YYYY-mm-dd. So, I tried to reverse to the format i was looking for to (MM/dd/yyyy).

But i cant get throught with validating every press that the user's typed. What happend was its validate as whole(regex) not one by one.

I also read his explanation about non-capturing group. But still, i can't get it.


Happy Coding!

Asked by:- Aileereal
: 8748 At:- 4/15/2018 12:25:10 PM
Javascript Regex

3 Answers
profileImage Answered by:- vikas_jk

You need regex like below for MM/dd/yyyy format


So your complete javascript code to test it would be

function validateDate() {
var testdate=document.getElementById('test').value;
    var date_regex = /^((0?[1-9]|1[012])[/](0?[1-9]|[12][0-9]|3[01])[/](19|20)?[0-9]{2})*$/ ;

Call it from html onChange

<input type="text" id="test" value="03/22/16" onchange="validateDate()">

You can use jQuery or javascript for calling the above function on change event, depends on your need the above call function on clicking tab etc.

here is the working fiddle link

This should work.

At:- 4/15/2018 5:46:20 PM

profileImage Answered by:- vikas_jk

Have you heard of jQuery KeyUp even, use it to validate input text on every button click, here is the function for it

function validateDate() {
var testdate=document.getElementById('test').value;
    var date_regex = /^((0?[1-9]|1[012])[/](0?[1-9]|[12][0-9]|3[01])[/](19|20)?[0-9]{2})*$/ ;
    var output=date_regex.test(testdate);
       $("#Output").html("Valid date");
     $("#Output").html("Not a valid date");
$( "#test" ).keyup(function() {


<input type="text" id="test" value="03/22/16" >

<div id="Output">


Here is the fiddle link

Now, If you want to change color's , you cannot do it in input textbox, you may need some editable content-box to do it, refer this link which has similar issue explained

Do not forget to upvote the comment/answer, if it helped you, thanks

At:- 4/16/2018 7:38:59 AM

profileImage Answered by:- Aileereal

I tested the code and it worked. But it is possible to do checking while typing? 

Like this but in MM/dd/yyyy format

Validating while typing

This one is what im trying to achieve. But in MM/dd/yyyy format. 

At:- 4/15/2018 10:00:54 PM
You can user jQuery KeyUp event as described in the second comment by Vikas, to validate input on each key value pressed for coloring output, I have no idea 0
By : Vinnu - at :- 4/18/2018 1:50:41 PM

Login/Register to answer
Register directly by posting answer/details

Full Name *

Email *

By posting your answer you agree on privacy policy & terms of use