Javascript 在日期字段中自动插入斜杠“/”的最佳方法是什么

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5005877/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:13:19  来源:igfitidea点击:

What's the best way to automatically insert slashes '/' in date fields

javascripthtml

提问by Shawn

I'm trying to add functionality to input date fields so as when the users enters in digits, slashes "/" get automatically added.

我正在尝试为输入日期字段添加功能,以便当用户输入数字时,会自动添加斜杠“/”。

So suppose I have the following html:

所以假设我有以下 html:

<input type="text" id="fooDate" />

And suppose I have the following javascript:

假设我有以下 javascript:

var dateField = document.getElementById("fooDate");
dateField.onkeyup = bar;

What should barbe?

应该bar是什么?

So far the best google result was:

到目前为止,最好的谷歌结果是:

function bar(evt)
{
    var v = this.value;
    if (v.match(/^\d{2}$/) !== null) {
        this.value = v + '/';
    } else if (v.match(/^\d{2}\/\d{2}$/) !== null) {
        this.value = v + '/';
    }

}

Thanks!

谢谢!

also -- I know having slashes being entered as you type sucks. Just roll with it :p

还有——我知道在你输入的时候输入斜线很糟糕。只需滚动它:p

回答by ChrisCoray

Update/Edit: Obviously the most simple solution today with widespread HTML5 support is to use <input type="date" name="yourName">.

更新/编辑:显然,当今具有广泛 HTML5 支持的最简单的解决方案是使用<input type="date" name="yourName">.

For those complaining that it doesn't accommodate backspaces or pasting, I modified the original:

对于那些抱怨它不适应退格或粘贴的人,我修改了原文:

//Put our input DOM element into a jQuery Object
var $jqDate = jQuery('input[name="jqueryDate"]');

//Bind keyup/keydown to the input
$jqDate.bind('keyup','keydown', function(e){

  //To accomdate for backspacing, we detect which key was pressed - if backspace, do nothing:
    if(e.which !== 8) { 
        var numChars = $jqDate.val().length;
        if(numChars === 2 || numChars === 5){
            var thisVal = $jqDate.val();
            thisVal += '/';
            $jqDate.val(thisVal);
        }
  }
});

`

`

Working Fiddle: https://jsfiddle.net/ChrisCoray/hLkjhsce/

工作小提琴:https: //jsfiddle.net/ChrisCoray/hLkjhsce/

回答by lynx_74

This is one simples way:

这是一种简单的方法:

Date: <input name=x size=10 maxlength=10  onkeyup="this.value=this.value.replace(/^(\d\d)(\d)$/g,'/').replace(/^(\d\d\/\d\d)(\d+)$/g,'/').replace(/[^\d\/]/g,'')">

Here ia a fiddle : https://jsfiddle.net/y6mnpc1j/

这里是一个小提琴:https://jsfiddle.net/y6mnpc1j/

回答by Asterius

// This solution also handle the delete and backspace keys:

jQuery('input[name="dateofbirth"]').bind('keyup',function(event){
    var key = event.keyCode || event.charCode;
    if (key == 8 || key == 46) return false;
    var strokes = $(this).val().length;

    if (strokes === 2 || strokes === 5){
        var thisVal = $(this).val();
        thisVal += '/';
        $(this).val(thisVal);
    }
    // if someone deletes the first slash and then types a number this handles it
    if (strokes>=3 && strokes<5){
        var thisVal = $(this).val();
        if (thisVal.charAt(2) !='/'){
             var txt1 = thisVal.slice(0, 2) + "/" + thisVal.slice(2);
             $(this).val(txt1);
        }
    }
    // if someone deletes the second slash and then types a number this handles it
    if (strokes>=6){
        var thisVal = $(this).val();
        if (thisVal.charAt(5) !='/'){
            var txt2 = thisVal.slice(0, 5) + "/" + thisVal.slice(5);
             $(this).val(txt2);
        }
    }
});

回答by ProgZi

Handles backspace, delete, paste, long press.

处理退格、删除、粘贴、长按。

let $jqDate = $('.date-slashes');

$jqDate.bind('keyup', function(ev) {
  if (ev.which !== 8) {
    let input = $jqDate.val();
    let out = input.replace(/\D/g, '');
    let len = out.length;

    if (len > 1 && len < 4) {
      out = out.substring(0, 2) + '/' + out.substring(2, 3);
    } else if (len >= 4) {
      out = out.substring(0, 2) + '/' + out.substring(2, 4) + '/' + out.substring(4, len);
      out = out.substring(0, 10)
    }
    $jqDate.val(out)
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<input name="dob" class="date-slashes" type="tel" maxlength="10" placeholder="mm/dd/yyyy">

回答by Lei Qin

My regex solution for React:

我的 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,
    });
  }

回答by TheSoulkiller

If you're looking for pure js version of @Chris's answer

如果您正在寻找@Chris 答案的纯 js 版本

var newInput = document.getElementById("theDate");
newInput.addEventListener('keydown', function( e ){
    if(e.which !== 8) {
        var numChars = e.target.value.length;
        if(numChars === 2 || numChars === 5){
            var thisVal = e.target.value;
            thisVal += '/';
            e.target.value = thisVal;
        }
    }
});

And HTML section might be(if necessary):

HTML 部分可能是(如有必要):

<input type="text" name="theDate" id="birthdate" maxlength="10"/>

回答by Steve Manatt

I spent some time working on the solution that Chris posted above and am accounting for everything except pasting, which isn't a requirement from the original poster as I read it.

我花了一些时间研究 Chris 在上面发布的解决方案,并考虑了除粘贴之外的所有内容,这不是我阅读原始海报时的要求。

//Bind keyup/keydown to the input
$('.date').bind('keyup', 'keydown', function(e) {
  //check for numerics
  var thisValue = $(this).val();
  thisValue = thisValue.replace(/[^0-9\//]/g, '');
  //get new value without letters
  $(this).val(thisValue);
  thisValue = $(this).val();
  var numChars = thisValue.length;
  $('#keyCount').html(numChars);
  var thisLen = thisValue.length - 1;
  var thisCharCode = thisValue.charCodeAt(thisLen);
  $('#keyP').html(thisCharCode);
  //To accomdate for backspacing, we detect which key was pressed - if backspace, do nothing:
  if (e.which !== 8) {
    if (numChars === 2) {
      if (thisCharCode == 47) {
        var thisV = '0' + thisValue;
        $(this).val(thisV);
      } else {
        thisValue += '/';
        $(this).val(thisValue);
      }
    }
    if (numChars === 5) {
      if (thisCharCode == 47) {
        var a = thisValue;
        var position = 3;
        var output = [a.slice(0, position), '0', a.slice(position)].join('');
        $(this).val(output);
      } else {
        thisValue += '/';
        $(this).val(thisValue);
      }
    }
    if (numChars > 10) {
      var output2 = thisValue.slice(0, 10);
      $(this).val(output2);
    }
  }
});
$('.date').blur(function() {
  var thisValue = $(this).val();
  var numChars = thisValue.length;
  if (numChars < 10) {
    $(this).addClass('brdErr');
    $('#dateErr1').slideDown('fast');
    $(this).select();
  } else {
    $(this).removeClass('brdErr');
    $('#dateErr1').hide();
  }
});

There is a lot added and a CSS class for an error message for invalid dates.

为无效日期的错误消息添加了很多内容和 CSS 类。

JSFiddle Here

JSFiddle在这里

回答by Luke Brandon Farrell

For react users, who want to perform the manipulation to the date before you sync it to the state, you can do this:

对于想要在将日期同步到状态之前对其进行操作的 react 用户,您可以执行以下操作:

onChangeText={(text) => {
   // Format the value and remove slashes, so addItemEvery will work
   let value = text.replace(/\/+/g, "");
   // We substring to add / to only the first part, every two characters
   const firstFourChars = addItemEvery(value.substring(0, 5), "/", 2);
   value = firstFourChars + value.substring(5, value.length);


   ... e.g. update state
}

...

function addItemEvery(str, item, every) {
  for (let i = 0; i < str.length; i++) {
     if (!(i % (every + 1))) {
        str = str.substring(0, i) + item + str.substring(i);
     }
  }

  return str.substring(1);
}

回答by alexl

Try to use this plugin : http://digitalbush.com/projects/masked-input-plugin/It works with jquery.

尝试使用这个插件:http: //digitalbush.com/projects/masked-input-plugin/它适用于 jquery。

回答by Vinay

This solution works for me. I have captured the blur event though you will have to change the code if you want to use keyup event. HTML

这个解决方案对我有用。我已经捕获了 blur 事件,但如果您想使用 keyup 事件,则必须更改代码。HTML

<input type="text" id="fooDate" onblur="bar(this)"/>

Javascript

Javascript

function bar(txtBox) {
  if (txtBox == null) {
    return ''
  }

  var re = new RegExp(/(\d{6})(\d{2})?/);

  if (re.test(txtBox.value)) {
    if (txtBox.value.length == 8) {
      txtBox.value = txtBox.value.substring(0, 2) + '/' + txtBox.value.substring(2, 4) + '/' + txtBox.value.substring(4, 8)
    }
    if (txtBox.value.length == 7) {
      txtBox.value = txtBox.value.substring(0, 2) + '/' + txtBox.value.substring(2, 3) + '/' + txtBox.value.substring(3, 8)
    }

    if (txtBox.value.length == 6) {
      if (txtBox.value.substring(4, 6) < 20) {
        txtBox.value = txtBox.value.substring(0, 2) + '/' + txtBox.value.substring(2, 4) + '/20' + txtBox.value.substring(4, 6);
      } else {
        txtBox.value = txtBox.value.substring(0, 2) + '/' + txtBox.value.substring(2, 4) + '/19' + txtBox.value.substring(4, 6);
      }
    }
  }
  return txtBox.value;
}