使用Javascript自动斜杠(/)进行日期输入

时间:2017-05-23 14:43:52

标签: javascript

在日期值中带有前导和尾随空格的自动斜杠(/)工作正常。

var date = document.getElementById('date');

    function checkValue(str, max) {
      if (str.charAt(0) !== '0' || str == '00') {
        var num = parseInt(str);
        if (isNaN(num) || num <= 0 || num > max) num = 1;
        str = num > parseInt(max.toString().charAt(0)) 
               && num.toString().length == 1 ? '0' + num : num.toString();
      };
      return str;
    };

    date.addEventListener('input', function(e) {
      this.type = 'text';
      var input = this.value;
      if (/\D\/$/.test(input)) input = input.substr(0, input.length - 3);
      var values = input.split('/').map(function(v) {
        return v.replace(/\D/g, '')
      });
      if (values[0]) values[0] = checkValue(values[0], 12);
      if (values[1]) values[1] = checkValue(values[1], 31);
      var output = values.map(function(v, i) {
        return v.length == 2 && i < 2 ? v + ' / ' : v;
      });
      this.value = output.join('').substr(0, 14);
    });
<input type="text" id="date" /> 

但是当我尝试删除斜杠(/)之前和之后的空格时。 但是当我使用退格键删除每个字符时,斜杠不会被删除。

以下是我的尝试。

var date = document.getElementById('date');

    function checkValue(str, max) {
      if (str.charAt(0) !== '0' || str == '00') {
        var num = parseInt(str);
        if (isNaN(num) || num <= 0 || num > max) num = 1;
        str = num > parseInt(max.toString().charAt(0)) 
               && num.toString().length == 1 ? '0' + num : num.toString();
      };
      return str;
    };

    date.addEventListener('input', function(e) {
      this.type = 'text';
      var input = this.value;
      if (/\D\/$/.test(input)) input = input.substr(0, input.length - 1);
      var values = input.split('/').map(function(v) {
        return v.replace(/\D/g, '')
      });
      if (values[0]) values[0] = checkValue(values[0], 12);
      if (values[1]) values[1] = checkValue(values[1], 31);
      var output = values.map(function(v, i) {
        return v.length == 2 && i < 2 ? v + '/' : v;
      });
      this.value = output.join('').substr(0, 10);
    });
<input type="text" id="date" /> 


    

请建议我纠正这个问题。

4 个答案:

答案 0 :(得分:5)

var date = document.getElementById('date');

    function checkValue(str, max) {
      if (str.charAt(0) !== '0' || str == '00') {
        var num = parseInt(str);
        if (isNaN(num) || num <= 0 || num > max) num = 1;
        str = num > parseInt(max.toString().charAt(0)) 
               && num.toString().length == 1 ? '0' + num : num.toString();
      };
      return str;
    };

    date.addEventListener('input', function(e) {
      this.type = 'text';
      var input = this.value;
      if (/\D\/$/.test(input)) input = input.substr(0, input.length - 3);
      var values = input.split('/').map(function(v) {
        return v.replace(/\D/g, '')
      });
      if (values[0]) values[0] = checkValue(values[0], 12);
      if (values[1]) values[1] = checkValue(values[1], 31);
      var output = values.map(function(v, i) {
        return v.length == 2 && i < 2 ? v + ' / ' : v;
      });
      this.value = output.join('').substr(0, 14);
    });
input {
    word-spacing:-3px;
}
<input type="text" id="date" />

你可以'欺骗'并使用一些CSS:

word-spacing:-3px;

这会使/更接近文字。

当您从JavaScript中删除空格时它不起作用的原因是因为您的代码正在查找字符串长度2,但是当您添加时,字符串长度将转到3 /没有空格。

答案 1 :(得分:2)

即使Albzi's answer完美无缺,这里也是一个替代答案。您可以使用function functionA<T>(funcThatReturnsT: (something: any) => T, funcThatTakeT: (t: T) => any) { let something = undefined as any; let hasTypeT = funcThatReturnsT(something); return funcThatTakeT(hasTypeT); } let aNumber = 5; // works functionA(() => aNumber, shouldBeInferedToBeANumber => shouldBeInferedToBeANumber.toExponential()); // still works functionA(_ => aNumber, shouldBeInferedToBeANumber => shouldBeInferedToBeANumber.toExponential()); /** * this is the same as `functionA` but it takes a configuraton object instead */ function functionAThatTakesAnObject<T>(opts: { funcThatReturnsT: (something: any) => T, funcThatTakeT: (t: T) => any }) { let something = undefined as any; let hasTypeT = opts.funcThatReturnsT(something); return opts.funcThatTakeT(hasTypeT); } // works functionAThatTakesAnObject({ funcThatReturnsT: () => aNumber, // if there is no parameter, it works funcThatTakeT: shouldBeInferedToBeANumber => shouldBeInferedToBeANumber.toExponential() }); // DOES NOT WORK functionAThatTakesAnObject({ funcThatReturnsT: _ => aNumber, // if there is a parameter, it breaks funcThatTakeT: shouldBeInferedToBeANumber => shouldBeInferedToBeANumber.toExponential() }); 事件并检查是否正在按下退格键或删除键,并在活动中keydown。我还在return false元素中添加了maxlength 10,因此不超过10个字符。

&#13;
&#13;
input
&#13;
var date = document.getElementById('date');

function checkValue(str, max) {
  if (str.charAt(0) !== '0' || str == '00') {
    var num = parseInt(str);
    if (isNaN(num) || num <= 0 || num > max) num = 1;
    str = num > parseInt(max.toString().charAt(0)) && num.toString().length == 1 ? '0' + num : num.toString();
  };
  return str;
};

date.addEventListener('keydown', function(e) {
  this.type = 'text';
  var input = this.value;
  var key = e.keyCode || e.charCode;

  if (key == 8 || key == 46)    // here's where it checks if backspace or delete is being pressed
    return false;
    
  if (/\D\/$/.test(input)) input = input.substr(0, input.length - 1);
  var values = input.split('/').map(function(v) {
    return v.replace(/\D/g, '')
  });
  if (values[0]) values[0] = checkValue(values[0], 12);
  if (values[1]) values[1] = checkValue(values[1], 31);
  var output = values.map(function(v, i) {
    return v.length == 2 && i < 2 ? v + '/' : v;
  });
  this.value = output.join('').substr(0, 10);
});
&#13;
&#13;
&#13;

答案 2 :(得分:1)

我也将这个作为我正在构建的应用程序的一个要求,并且我实现了我的解决方案。

$(document).ready(function () {
    Date.prototype.toShortDateString = function() {
        return (this.getMonth() + 1) + "/" + this.getDate() + "/" + this.getFullYear();
    }
    //#region CUSTOM FUNCTIONS FOR DATEPICKERS
    function isTextSelected(input) {
        if (typeof input.selectionStart == "number" && input.selectionStart != input.value.length && input.selectionStart != input.selectionEnd) {
            return true;
        } else if (typeof document.selection != "undefined") {
            input.focus();
            return document.selection.createRange().text == input.value;
        }
        return false;
    }
    function isNumber(e) {
        var allowedKeys = [48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105];
        if ($.inArray(e.keyCode, allowedKeys) != -1 && !e.originalEvent.shiftKey) {
            return true;
        }
        return false;
    }
    function isBackspace(keyCode) {
        var allowedKeys = [8];
        if ($.inArray(keyCode, allowedKeys) != -1) {
            return true;
        }
        return false;
    }
    function isAllowedKey(keyCode) {
        var allowedKeys = [9, 13, 16, 37, 38, 39, 40];//191,111];
        if ($.inArray(keyCode, allowedKeys) != -1) {
            return true;
        }
        return false;
    }
    //#endregion
    $.fn.extend({
        allowMMDDYYYY: function (validate) {
            $(this).keydown(function (e) {
                var that = this;
                if (!isNumber(e) && !isBackspace(e.keyCode) && !isAllowedKey(e.keyCode)) {
                    e.preventDefault();
                } else if ($(that).val().length == 10 && !isBackspace(e.keyCode) && !isAllowedKey(e.keyCode)) {// && !isTextSelected(e.target) && isNumber(e.keyCode)) {
                    if(!isTextSelected(e.target) && isNumber(e))
                    e.preventDefault();
                }
            });
            $(this).keyup(function (e) {
                var that = this;
                var value = $(that).val();
                if (e.keyCode != 8 && !isAllowedKey(e.keyCode)) {
                    switch (value.length) {
                        case 2:
                            $(that).val(value + "/");
                            break;
                        case 3:
                            if (value.indexOf("/") == -1) {
                                $(that).val(value.substr(0, 2) + "/" + value.substr(2, 1));
                            }
                            break;
                        case 4:
                            if (value.substr(0,3).indexOf("/") == -1) {
                                $(that).val(value.substr(0, 2) + "/" + value.substr(2, 2));
                            }
                            break;
                        case 5:
                            if (e.target.selectionStart == value.length) {
                                if (e.target.selectionStart != 1) {
                                    $(that).val(value + "/");
                                }
                            }
                            break;
                        case 6:
                            if (e.target.selectionStart == value.length) {
                                if (value.substr(5).indexOf("/") == -1) {
                                    $(that).val(value.substr(0, 5) + "/" + value.substr(5, 1));
                                }
                            } else if (e.target.selectionStart == 2) {
                                $(that).val(value.substr(0, 2) + "/" + value.substr(2))
                                e.target.selectionStart = 3;
                                e.target.selectionEnd = 3;
                            }
                            break;
                        case 7:
                            if (e.target.selectionStart == value.length) {
                                if (value.substr(5).indexOf("/") == -1) {
                                    $(that).val(value.substr(0, 6) + "/" + value.substr(5, 2));
                                }
                            } else if (e.target.selectionStart == 2) {
                                $(that).val(value.substr(0, 2) + "/" + value.substr(2));
                                e.target.selectionStart = 3;
                                e.target.selectionEnd = 3;
                            }
                            break;
                        case 9:
                            if (value.substr(3, 5).indexOf("/") == -1) {
                                $(that).val(value.substr(0,5) + "/" + value.substr(5))
                            } else if (value.substr(0, 3).indexOf("/") == -1) {
                                $(that).val(value.substr(0, 2) + "/" + value.substr(2))
                            }
                            break;
                            //IF THE LENGTH IS 10 (ONKEYUP) THEN CALL VALIDATION ON OTHER DATEPICKER ELEMENTS.
                        case 10:
                            if (!isTextSelected(e.target)) {
                                validate();
                            }
                            break;
                    }
                }
            });
        }
    });
    //#endregion
    $("input[data-role='datepicker']").each(function (i, o) {
        var jqueryElement = $(o);
        jqueryElement.allowMMDDYYYY(function () {
            //THIS IS MY CALLBACK FUNCTION TO ALLOW VALIDATION ON OTHER ELEMENTS 
            console.log("validating");
        });
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" data-role="datepicker"/>

我要求我们能够在没有斜线的情况下输入MMddyyyy格式,它会在键入时自动填充斜杠。解决方案不允许任何字符,但数字,退格键,箭头键,ctrl和shift键。此扩展还具有回调函数,以便您可以在输入日期后验证其他元素(因为我使用的是jquery验证程序)。

答案 3 :(得分:0)

这是我的React正则表达式解决方案:

// add auto "/" for date, i.e. MM/YY
  handleExpInput(e) {

    // ignore invalid input
    if (!/^\d{0,2}\/?\d{0,2}$/.test(e.target.value)) {
      return;
    }

    let input = e.target.value;

    if (/^\d{3,}$/.test(input)) {
      input = input.match(new RegExp('.{1,2}', 'g')).join('/');
    }

    this.setState({
      expDateShow: input,
    });
  }