Skip to content

Instantly share code, notes, and snippets.

@zavan
Last active October 7, 2020 16:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zavan/fc37a1e18d404d8df430790e5b3e2e24 to your computer and use it in GitHub Desktop.
Save zavan/fc37a1e18d404d8df430790e5b3e2e24 to your computer and use it in GitHub Desktop.
Pure JS MM/DD input masking
<input id="input-id" placeholder="MM/DD" maxlength="5">
<script src="./mmdd_mask.js"></script>
<script>
var el = document.getElementById('#input-id');
var mmddMask = new MMDDMask(el);
</script>
function MMDDMask(element) {
this.element = element;
this.attachEventHandlers();
}
MMDDMask.prototype.getElement = function() {
return this.element;
}
MMDDMask.prototype.mask = function(value) {
// Remove non-numeric chars and trim to 4 chars
var v = value.replace(/\D/g, '').slice(0, 4);
var fullRegex = /^(0[1-9]|1[0-2])(0[1-9]|1\d|2\d|3[01])$/;
switch (v.length) {
case 1:
var dateRegex = /^(0|1)$/;
if (!dateRegex.test(v)) return '';
break;
case 2:
var dateRegex = /^(0[1-9]|1[0-2])$/;
if (!dateRegex.test(v)) return v.slice(0, 1);
break;
case 3:
var dateRegex = /^(0[1-9]|1[0-2])([0-3])$/;
if (!dateRegex.test(v)) return v.slice(0, 2) + '/';
break;
case 4:
if (!fullRegex.test(v)) return v.slice(0, 2) + '/' + v.slice(2, 3);
break;
}
if (v.length >= 4 && !fullRegex.test(v)) return '';
if (v.length >= 2) return v.slice(0, 2) + '/' + v.slice(2, 4);
return v;
}
MMDDMask.prototype.handleEvent = function(e) {
var key = e.keyCode || e.charCode;
// Allow backspace and delete.
if (key === 8 || key === 46) return true;
e.target.value = this.mask(e.target.value);
}
MMDDMask.prototype.attachEventHandlers = function() {
this.getElement().addEventListener('keyup', this.handleEvent.bind(this));
// keyup is not fired if a value is pasted using the mouse only.
this.getElement().addEventListener('change', this.handleEvent.bind(this));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment