jQuery – Auto slash(/) in date field

Automatically formating TextBox to dd/MM/yyyy while typing using jQuery
Example here: jsfiddle.net/DotMaui/2g6ayjp5/1/

$(".my-date").on("keypress keyup",function (event) {

    if (event.key == "/" && $(this).val().length != 2 && $(this).val().length != 5) {
        event.preventDefault();
    }
    else if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57) && event.key != "/") {
        event.preventDefault();
    }
}).on("keyup", function (e) {
    ValidateDateFormat($(this)[0], e);
}).attr("maxlength", 10)
  .attr("placeholder", "DD/MM/YYYY");

function ValidateDateFormat(input, e) {

    let seperator = "/";
    let keyCode = e.keyCode;

    if (((keyCode >= 48 && keyCode <= 57) || keyCode == 8 || keyCode <= 37 || keyCode <= 39 || (keyCode >= 96 && keyCode <= 105)) && keyCode != 16) {

        if ((input.value.length == 2 || input.value.length == 5) && keyCode != 8) {
            input.value += seperator;
        }
        return true;
    }
    else {
        return false;
    }

};

Leave a Comment

Your email address will not be published. Required fields are marked *