can you add an auto slash in date2000-12-30 using javascript?

Try like this:

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[1]) values[1] = checkValue(values[1], 12);
  if (values[2]) values[2] = checkValue(values[2], 31);

  var max = 4;
  var output = values.map(function(v, i) {
    if (v.length == max) {
      max = 2;
      return i < max ? v + ' / ' : v;
    };

    return v;
  });
  this.value = output.join('').substr(0, 14);
});
<input type="text" id="date">

When mapping the values to set the output, the first element should be checked against the length of yyyy (4) and the others against the length of mm or dd (2). Finally, the indexes of the values passed into checkValue need to be incremented.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top