Converting regular text input into DD/MM/YYYY format

Viewed 1766

I can only use type="text" and I'm planning to get the format DD/MM/YYYY as the user types in the input field.

So far, I manage to get DD/MM/YY/Y. The year should be in YYYY format. How do I go about this?

$('[data-type="date"]').keyup(function() {
      var value = $(this).val();
      value = value.replace(/\D/g, "").split(/(?:([\d]{2}))/g).filter(s => s.length > 0).join("/");
      $(this).val(value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<input type="text" pattern="[0-9]*" data-type="date" maxLength="10" id="date" class="form-control" placeholder="DD/MM/YYYY">

4 Answers

You could try and use an external plugin for this. A quick search shows a few including this one.

Here's how it should work:

$(document).ready(function(){
  $('.date').mask('00/00/0000');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.15/jquery.mask.min.js"></script>
<input type="text" class="date">

Don't forget to validate the input, though.

You can use the following solution to convert regular text input into DD/MM/YYYY format:

$('[data-type="date"]').keyup(function(event) {
    var value = $(this).val();
    if (event.keyCode !== 8 && value.indexOf("/") === value.lastIndexOf("/")) {
        if (value.length > 2 && value[2] != "/") {
            value = value.substring(0, 2) + "/" + value.substring(2);
        } 

        if (value.length > 5 && value[5] != "/") {
            value = value.substring(0, 5) + "/" + value.substring(5);
        }
    }
    $(this).val(value);
});

You can use jQuery Mask Plugin. For installation information

$('[data-type="date"]').mask('00/00/0000');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.15/jquery.mask.min.js"></script>
<input type="text" pattern="[0-9]*" data-type="date" maxLength="10" id="date" class="form-control" placeholder="DD/MM/YYYY">

This will do what you want. It uses Array.reduce to put the /'s into the date string, testing to see if we are past the month, or already at the end of the string so as not to put in a / where it should not occur.

$('[data-type="date"]').keyup(function() {
      var value = $(this).val();
      value = value.replace(/\D/g, "")
                   .split(/(..)/)
                   .filter(s => s.length > 0)
                   .reduce((t, v, i, a) => t + v + (i > 1 || i == a.length - 1 ? '' : '/'), '');
      $(this).val(value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<input type="text" pattern="[0-9]*" data-type="date" maxLength="10" id="date" class="form-control" placeholder="DD/MM/YYYY">

Related