Jquery Masked input with regex?

Asked

Viewed 1,766 times

3

I put the following script to put only month and year in input, and set 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, it only allows to enter a number, so if I want to put month 12, I can’t. Someone has some solution?

  • Your regex shouldn’t be "^([2-9]|1[0-2])$"?

  • @Victorstafusa The problem is the spacing, when I put only one X, it allows the typing of only one number, and if I put "XX" , not the right one, then it allows typing 22 , for example.

  • 1

    I don’t see how you can make it work (and I say from the usability point of view mainly). If the user has typed 1, Did he want the month January or will he still write another digit? It would be better to require zero... As to avoid months 13 or above, unfortunately I have nothing to suggest (that question on Soen and his answers imply that there is nothing ready in the plugin to do this, being necessary to customize with own code). By the way, you are using the plugin Masked, right?

  • I agree that @mgibsonbr said, I believe it is not possible, but providing the regex that I believe is the most appropriate var r = new RegExp('^0[1-9]|1[0-2]$')

  • Right! Thank you for the tips! I will validate in another way then. And yes @mgibsonbr, I am using Masked.

  • Did you solve your problem? @Ysabelle Sousa

Show 1 more comment

1 answer

1

It is possible to use the , changing the mask with the event onKeyPress, 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>

Browser other questions tagged

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