jQuery Date Mimic

Form date formatter with error message for invalid dates.

by manattweb

HTML

<div style="font-family: Helvetica,Arial,sans-serif; font-size: 12px; line-height: 150%;">
<p>Dependent on the "date" CSS class for the field, which means it can be applied to multiple date fields on a single form. There's an error message that gets shown if the date is too short and is hidden if the date is corrected.</p>
  Try to enter:
  <ul>
    <li>Letter</li>
    <li>One-digit month/day and then '/'</li>
    <li>5-digit year</li>
  </ul>
  <strong>jQuery "date" input:</strong> <input type="text" name="jqueryDate" class="date" placeholder="mm/dd/yyyy" max="10"><br>
  <div id="dateErr1" style="color: #ff0000; display: none;">THIS DOES NOT APPEAR TO BE A VALID DATE (MM/DD/YYYY). PLEASE REVIEW.<br></div>
  Key Input: <span id="keyP">null</span><br /> Key Count: <span id="keyCount">0</span>
</div>

CSS

.brdErr {
  border-color: #FF0000;
}

JavaScript

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