javascript – JQuery masked input com regex?

Question:

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 the X in, it only allows you to enter a number, so if I want to put month 12, I can't. Does anyone have any solutions?

Answer:

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>
<script src="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>
Scroll to Top