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:
https://stackoverflow.com/questions/36009414/regex-to-validate-date-yyyy-mm-dd-while-typing-on-keyup
(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!
You need regex like below for MM/dd/yyyy format
^((0?[1-9]|1[012])[/](0?[1-9]|[12][0-9]|3[01])[/](19|20)?[0-9]{2})*$
So your complete javascript code to test it would be
function validateDate() {
var testdate=document.getElementById('test').value;
console.log(testdate);
var date_regex = /^((0?[1-9]|1[012])[/](0?[1-9]|[12][0-9]|3[01])[/](19|20)?[0-9]{2})*$/ ;
alert(date_regex.test(testdate));
}
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 https://jsfiddle.net/1e8fxpm7/10/
This should work.
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;
console.log(testdate);
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);
if(output==true)
{
$("#Output").html("Valid date");
}
else
{
$("#Output").html("Not a valid date");
}
}
$( "#test" ).keyup(function() {
validateDate();
});
HTML
<input type="text" id="test" value="03/22/16" >
<div id="Output">
</div>
Here is the fiddle link https://jsfiddle.net/5x7gdrk6/2/
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 https://forum.jquery.com/topic/highlighting-changing-text-color-in-a-textbox-as-user-types
Do not forget to upvote the comment/answer, if it helped you, thanks
I tested the code and it worked. But it is possible to do checking while typing?
Like this but in MM/dd/yyyy format
This one is what im trying to achieve. But in MM/dd/yyyy format.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly