Auto-formatting date inputs are everywhere – some better than others. Anyway, for a recent project I had wanted to use the HTML5 date input but the date widgets that appeared were partially implemented in some browsers which made us remove them. Provided here is the script that I wrote to auto-correct the date while the user is typing, enforcing the desired format:
- Enforce MM/DD/YYYY formatting
- Forward slashes added as you type
- extra slashes are removed
To use this script add an event listener that listens for the keyup event that fires the function below.
You must also have jQuery embedded into your page.
function updateDobInput(e){ var input = $(e.target).val(); var slashQuan = input.match(/\//g); var groups = null; var str = ''; var key = e.which || e.keyCode || 0; var result; if (key === 8 || key === 46){ return; } // cannot start with a leading slash input = input.indexOf('/') === 0 && input.length === 1 ? '' : input; // remove multiple adjacent slashes while (input.indexOf('//') !== -1){ input = input.replace(/\/\//g,'/'); } // if more than two slashes remove the 3rd and everything that comes after if (slashQuan && slashQuan.length > 2){ input = input.substr(0,input.lastIndexOf('/')); } // capture the desired date pattern dd/dd/dddd groups = /^(\d{0,2})\/{0,1}(\d{0,2})\/{0,1}(\d{0,4})$/.exec(input); if (groups && groups[1]){ if (groups[1].length === 2){ str += groups[1] + '/'; } else { str += groups[1]; } } if (groups && groups[2]){ if (groups[2].length === 2){ str += groups[2] + '/'; } else { str += groups[2]; } } if (groups && groups[3]){ str += groups[3]; } result = str.length > 0 ? str : input; $(e.target).val(result); };