JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="year" data-fullyear="" placeholder="yyyy" maxlength="4">
JavaScript
// Restricts input for each element in the set of matched elements to the given inputFilter.
(function($) {
$.fn.inputFilter = function(inputFilter) {
return this.on("input keydown keyup mousedown mouseup select contextmenu drop", function() {
if (inputFilter(this.value)) {
this.oldValue = this.value;
this.oldSelectionStart = this.selectionStart;
this.oldSelectionEnd = this.selectionEnd;
} else if (this.hasOwnProperty("oldValue")) {
this.value = this.oldValue;
this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
}
});
};
}(jQuery));
$("#year")
.inputFilter(function(value) {
return /^\d*$/.test(value);
})
.on("blur",e=>{
let $this = $(e.currentTarget);
let value = $this.val();
if(value.length===4){
$this.data("fullyear",value)
$this.val(value.substring(2));
}else{
$this.data("fullyear","")
$this.val("");
}
})
.on("focus",e=>{
let $this = $(e.currentTarget);
let value = $this.val();
if(value.length===2){
let fullYear = $this.data("fullyear");
$this.val(fullYear);
}else{
$this.val("");
}
});