Skip to content

Instantly share code, notes, and snippets.

@mitnick78
Created December 10, 2018 11:16
Show Gist options
  • Save mitnick78/798ab55e6a6577e9612cf2324bd9a498 to your computer and use it in GitHub Desktop.
Save mitnick78/798ab55e6a6577e9612cf2324bd9a498 to your computer and use it in GitHub Desktop.
var birthDate = document.getElementById("id");
var format = "mm/dd/yyyy";
var match = new RegExp(format
.replace(/(\w+)\W(\w+)\W(\w+)/, "^\\s*($1)\\W*($2)?\\W*($3)?([0-9]*).*")
.replace(/m|d|y/g, "\\d"));
var replace = "$1/$2/$3$4"
.replace(/\//g, format.match(/\W/));
function format(target)
{
target.value = target.value
.replace(/(^|\W)(?=\d\W)/g, "$10") // padding
.replace(match, replace) // fields
.replace(/(\W)+/g, "$1"); // remove repeats
}
birthDate.addEventListener( 'keyup', function(e){
if(!e.ctrlKey && !e.metaKey && (e.keyCode == 32 || e.keyCode > 46))
format(e.target)
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment