<input type="text" placeholder="MM/YY">
input {
  width: 250px;
  font-size: 4em;
}
const input = document.querySelector('input');

const prepare = (value, clamper) => {
  if (value === '0') {
    return value;
  } else {
    const parsedValue = parseInt(value);
    if (!isNaN(parsedValue)) {
      const clampedValue = clamper(parsedValue);

      if (value.startsWith('0') && clampedValue > 0 && clampedValue <= 9) {
        return `0${clampedValue}`;
      } else {
        return clampedValue.toString();
      } 
    } else {
      return '';
    }
  }
};

const normalize = (value, addDelimiter = false) => {
  const [month, year] = value.split('/').map(entry => {
    return entry.replace(/^D/g, '').trim();
  });
  const parsed = {
    month: null,
    year: null,
    hasDelimiter: year !== undefined
  };
  
  if (month !== undefined && month !== '') {
    parsed.month = prepare(month, parsedMonth => Math.max(1, Math.min(12, parsedMonth)));
    
    if (addDelimiter) {
      const _month = Number(parsed.month);
      if (_month >= 10) {
        parsed.hasDelimiter = true;
      }
    }
  }
  
  if (year !== undefined && year !== '') {
    parsed.year = prepare(year, parsedYear => Math.max(0, Math.min(70, parsedYear)));
  }
  
  if ((parsed.month === null || parsed.month === '0') && parsed.year !== null) {
    parsed.month = '1';
  }
  
  if (parsed.month !== null || parsed.year !== null) {
    const preparedMonth = parsed.hasDelimiter ? parsed.month.padStart(2, 0) : parsed.month;
    const normalized = `${preparedMonth}${parsed.hasDelimiter ? '/' : ''}${parsed.year || ''}`;
    
    return normalized;
  } else {
    return value;
  }
};

input.addEventListener('input', event => {
  console.log('event.inputType', event.inputType)
  const normalizedValue = normalize(event.target.value, !event.inputType.startsWith('deleteContent'));
  
  if (event.target.value !== normalizedValue) {
    event.target.value = normalizedValue;
  }
});

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.