How to do date masking using javascript (without JQuery)?

后端 未结 4 620
太阳男子
太阳男子 2020-12-09 00:26


        
4条回答
  •  不知归路
    2020-12-09 00:57

    Try out this code, this will format your date in mm/dd/yyyy format as you type it in the input box. Create an onchange event on the input box and call the date_formator function with the input date.

    function date_formator(date) {
    
        date = date.replace('//', '/');
        var result = date.split("/");
    
        var length = result.length;
    
        // Append "/" after the last two charas, if more than 2 charas then remove it
        if (length <= 2 && result[length - 1] != "") {
            var last_two_digits = result[length -1];
            if (last_two_digits.length >= 2) {
                date = date.slice(0, -last_two_digits.length);
                date = date + last_two_digits.slice(0,2) + "/";
            }
        }
    
        if (typeof result[2] != "undefined") {
            var year = result[2];
            if (year.length > 4) {
                date = date.slice(0, -year.length);
                year = year.slice(0, 4);
                date = date + year;
            }
        }
        return date;
    }
    

提交回复
热议问题