How to configure jquery.maskedinput to accept valid dates only?

Asked

Viewed 294 times

0

How do I make for the <input type="text" name="calendar" id="calendar"> accept only correct dates, example of a correct date 01/02/2017 but it is accepting when type 01/20/2017, ie the month 20 does not exist, the type of <input> must continue with "text", follow the example with the problem.

$(document).ready(function(){
  $('#calendar').mask('99/99/9999');
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.maskedinput/1.4.1/jquery.maskedinput.min.js"></script>
<input type="text" id="calendar" name="calendar">

  • Why it needs to be text?

  • @Thiagosantos why it could not be text?

  • It could be "date".

  • This isn’t HTML5 it’s just jQuery.

  • @Thiagosantos besides being js, type="date" does not work in Firefox, IE and Safari: http://caniuse.com/#search=input%20date

  • date does not work in firefox, so the alternative was to use the jquery mask.

  • @Wagnerfernandomomesso I wrote a solution (below) using JS and without changing "text" that erases the field if the date does not exist, can check?

Show 2 more comments

2 answers

2

1


I believe that’s it:

$(document).ready(function(){
  $('#calendar').mask('99/99/9999');
  });

function validateData(){

    var dob = document.getElementById("calendar").value;
    var data = dob.split("/");

    if (isNaN(Date.parse(data[2] + "-" + data[1] + "-" + data[0]))) {
        document.getElementById("calendar").value = "";
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.maskedinput/1.4.1/jquery.maskedinput.min.js"></script>
<input type="text" onBlur="validateData()" id="calendar" name="calendar">

  • solved my problem, thank you very much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.