JSFiddle - React, Tailwind, and code Playground
HTML
<input type='text' id='sdate' maxlength='10' value='mm/dd/yyyy' />
<input type='button' id='validate' value='Check date in console' />
JavaScript
(function(dateIn, btn)
{
var clear = function(e)
{//first two lines are to ensure X-browser compat with IE < 9
e = e || window.event;
var el = e.target || e.srcElement;
if (el.value === 'mm/dd/yyyy')
{//if default value is set, clear
el.value = '';
}
//this event needs to be handled but once, so remove listener
//add listener for click event to button
if (el.removeEventListener)
{
btn.addEventListener('click',validate,false);
el.removeEventListener('focus',clear,false);
return e;
}
btn.addEventListener('onclick',validate);
el.detachEvent('onfocus',clear);//IE < 9
},
keypress = function(e)
{
e = e || window.event;
var el = e.target || e.srcElement,
char = String.fromCharCode(e.keyCode || e.which);//some more IE quirks
e.returnValue = false;
e.cancelBubble = true;//officially deprecated, but old IE...
if (e.preventDefault)
{
e.preventDefault();
e.stopPropagation();
}
if (char == +(char) && el.value.length < 10)
{//char is numeric, and total string < 10, add char to value string
//basic date format checks... you need to work on these, though:
switch (el.value.length)
{
case 0:
if (char > 1)
{//invalid month format
alert('date format should be mm/dd/yyyy');
return e;
//or turn 2, for example, into 02:
char = '0' + char;
}
break;
case 3:
if (char > 3)
{
alert(char + ' is not a valid day');
return e;
...