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 doFormat(target)
{
target.value = target.value
.replace(/(^|\W)(?=\d\W)/g, "$10") // padding
.replace(match, replace) // fields
.replace(/(\W)+/g, "$1"); // remove repeats
}
$(".birthdate-input").keyup(function(e) {
if(!e.ctrlKey && !e.metaKey && (e.keyCode == 32 || e.keyCode > 46))
doFormat(e.target)
});
// don't let type letters into the birthdate input fields
$(".birthdate-input")[0].onkeypress = function(e) {
e = e || event;
if (e.ctrlKey || e.altKey || e.metaKey) return;
var chr = getChar(e);
if (chr == null) return;
if (chr < '0' || chr > '9') {
return false;
}
}
function getChar(event) {
if (event.which == null) {
if (event.keyCode < 32) return null;
return String.fromCharCode(event.keyCode) // IE
}
if (event.which != 0 && event.charCode != 0) {
if (event.which < 32) return null;
return String.fromCharCode(event.which) // other
}
return null; // special key
}