Подтвердить что ты не робот

Какой лучший способ автоматически вставлять косы '/' в поля даты

Я пытаюсь добавить функциональность для ввода полей даты, так что, когда пользователи вводят цифры, косые черты "/" автоматически добавляются.

Итак, предположим, что у меня есть следующий html:

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

И предположим, что у меня есть следующий javascript:

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

Что должно bar быть?

До сих пор лучшим результатом Google был:

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 + '/';
    }

}

Спасибо!

также - я знаю, что косые слова вводятся, когда вы печатаете отстой. Просто сверните с ним: p

4b9b3361

Ответ 1

Обновление/Редактирование: Очевидно, что самым простым решением сегодня с широко распространенной поддержкой HTML5 является использование <input type="date" name="yourName">.

Для тех, кто жалуется, что он не вмещает обратные пространства или вставку, я изменил оригинал:

//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);
        }
  }
});

`

Рабочий скрипт: https://jsfiddle.net/ChrisCoray/hLkjhsce/

Ответ 2

Это один простой способ:

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

Ответ 3

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);
        }
    }

});

Ответ 4

У меня есть альтернатива, которая может работать с jquery-ui datepicker, без formatter.js. Он предназначен для вызова из событий keyup и change. Он добавляет нулевое дополнение. Он работает с различными поддерживаемыми форматами дат, создавая выражения из строки dateFormat. Я не могу придумать способ сделать это с заменой менее трех.

// Example: mm/dd/yy or yy-mm-dd
var format = $(".ui-datepicker").datepicker("option", "dateFormat");

var match = new RegExp(format
    .replace(/(\w+)\W(\w+)\W(\w+)/, "^\\s*($1)\\W*($2)?\\W*($3)?([0-9]*).*")
    .replace(/mm|dd/g, "\\d{2}")
    .replace(/yy/g, "\\d{4}"));
var replace = "$1/$2/$3$4"
    .replace(/\//g, format.match(/\W/));

function doFormat(target)
{
    target.value = target.value
        .replace(/(^|\W)(?=\d\W)/g, "$10")   // padding
        .replace(match, replace)             // fields
        .replace(/(\W)+/g, "$1");            // remove repeats
}

https://jsfiddle.net/4msunL6k/

Ответ 6

Это решение работает для меня. Я захватил событие размытия, хотя вам придется изменить код, если вы хотите использовать событие keyup. HTML

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

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;
}

Ответ 7

Если вы ищете чистую js-версию @Chris answer

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;
        }
    }
});

И раздел HTML может быть (если необходимо):

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

Ответ 8

Я потратил некоторое время на работу над решением, которое Крис опубликовал выше, и я учитываю все, кроме вставки, что не является требованием к первоначальному постеру, когда я его читал.

//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();
  }
});

Там много добавлено и CSS класс для сообщения об ошибке для недействительных дат.

JSFiddle Здесь

Ответ 9

Для реагирующих пользователей, которые хотят выполнить манипуляции с датой, прежде чем синхронизировать ее с состоянием, вы можете сделать это:

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);
}