Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Masked input Plugin with date limit

I use masked input on a input text field for a date in the MM/YYYY format. ( http://digitalbush.com/projects/masked-input-plugin/ )

My javascript code:

jQuery(function($){
   $(".date").mask("12/2099");
});

And HTML Code:

<input type="text" class="date">

When I start to write something it take to the field the value 12/2099 and it's impossible to write other thing.

If in javascript mask I write 99/9999, users could write date that is false ... so I don't what I have to do ?

I want to users that they could write starting on 01/1990 until 12/2099, possible adding to the restrict with the value of the date + 20 years or something like that ...

like image 748
Tomaw Avatar asked Jun 04 '26 19:06

Tomaw


1 Answers

Well, I think is good to have the masked input but I prefer to validate the input value cause these kind of plugins generally works with regex from inside.

My solution for this could be:

(EDITED AND TESTED)

Adding a div for a message

<form id="frm">
    <input type="text" class="date">
    <div id="msg"></div>
    <input type="submit" value="Click Me"/>
</form>

the js:

     <script type="text/javascript">

            function verifyDate(datevalue) {

              var done = false;

              if(datevalue != null || datevalue != ''){

                //split the date as a tmp var
                var tmp = datevalue.split('/');

                //get the month and year
                var month = tmp[0];
                var year = tmp[1];

               if(month >= 1 && month <= 12){
                  if(year >= 1990 && year <= 2099){

                   //clean the message
                   clean();

                   //finally, allow the user to pass the submit
                   done = true;

                  } else {
                    $('#msg').html('Year must be from 1990 - 2099.');
                  }
               } else {
                  $('#msg').html('Month is invalid.');
               }
            }
            return done;
          }

          function clean() {
             $('#msg').html('');
          }

          jQuery(function($) {

             //mask the input
             $(".date").mask("12/2099");

             $('#frm').submit(function() {
                var datevalue = $('.date').val();
                return verifyDate(datevalue)           
             });

             $(".date").keyup(function(){
                //get the date
                var datevalue = $(this).val();

                //only if the date is full like this: 'xx/xxxx' continue
                if(datevalue.length == 7) {               
                  verifyDate(datevalue);
                } else {
                  clean();
                }
             });

          });

    </script>

Hope this helps.

Regards.

like image 111
Oscar Jara Avatar answered Jun 07 '26 15:06

Oscar Jara