JSFiddle - React, Tailwind, and code Playground
by konijn_gmail_com
HTML
<form action="#">
<label>Date 1<input id='d1' type='text'/> <span>I am here</span></label><br>
<label>Date 2<input id='d2' type='text'/> <span>I am here</span></label>
</form>
CSS
input[type=text] {
border:1px solid lightblue;
border-radius:5px;
padding:10px;
}
span{
color:red;
display:none;
}
JavaScript
DateHandler = (function(){
var $dateField,
mandatory,
value;
function DateField( elementId, _mandatory ){
console.log('!');
$dateField = $( '#' + elementId );
mandatory = _mandatory || false;
$dateField.on('keyup focusout', validate );
}
function validate(){
error( '' );
var text = $dateField.val().toUpperCase(), matches;
if( text.length == 0 ){
if( mandatory ){
error( 'Field should not be empty' );
}
return;
} else if( text.length == 6 ){
matches = /([0-3][0-9])([0-1][0-9])(\d\d)/.exec(text);
} else if( text.length == 7 ){
matches = /([0-3][0-9])(\w\w\w)(\d\d)/.exec(text);
}
if(!matches){
return error( 'Field should be of format DDMMYY or DDMMMYY' );
}
value = new Date( matches[2] + ' ' + matches[1] + " " + ( matches[3] < 50 ? "20" : 19 ) + matches[3] );
console.log( value );
}
function error( message ){
var label = $dateField.siblings('span');
message ? label.html(message).show() : label.hide();
}
return DateField;
}());
var dateHandler = DateHandler( 'd1' );