JQuery masked input with regex?

3

I put the following script to put only month and year in the input, and set the regex to accept typing from 1 to 12 for months:

            $.mask.definitions['X'] = "^([0-1]|1[0-2])$";
            jQuery(function($){
               $("#masked1").mask("X/9999");
               $("#masked2").mask("X/2015");                    
            });

But when I put X, it only allows you to enter a number, so if I want to put month 12, I can not. Does anyone have a solution?

    
asked by anonymous 04.11.2015 / 17:07

1 answer

1

You can use , changing the mask with the onKeyPress event, depending on whether the month has a value equal to or greater than 10.

var mask = function (val) {
    val = parseInt(val);
    return (val == 1 || val > 9)? "UD" : "N";
}

pattern = {
    onKeyPress: function(val, e, field, options) {
        field.mask(mask.apply({}, arguments), options);
    },
    translation: {
        'U': { pattern: /1/, optional: false },
        'D': { pattern: /[0-2]/, optional: false },
        'N': { pattern: /[1-9]/, optional: false }
    },
    placeholder: 'mês'
};

$(document).ready(function () {
  $("#masked2").mask(mask, pattern);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.0/jquery.mask.min.js"></script>

<label>
  Mês:
  <input type="text" id="masked2" />
</label>
    
09.10.2016 / 10:57