Search code examples
javascriptjqueryhtmljquery-mask

jQuery Mask with optional char


I have been using jquery mask plugin in my application to mask some fields. It works fine. I have to mask car plates in brazilian format (3 letters and 4 numbers separeted by -) and the code bellow always worked fine:

$(".car-plate").mask("AAA-0000");

Now, I have to provide the new format which increase a optional letter, it means: AAAA-0000. I have to keep the current format to be compatible. Sometimes the car plate can be AAA-0000 and sometimes AAAA-0000. I have tried it:

var carMaskBehavior = function (val) {    
  return val.replace(/\W/g, '').length === 8 ? 'AAAA-AAAA' : 'AAA-AAAA';
},      
spOptions = {
  onKeyPress: function(val, e, field, options) {
      field.mask(carMaskBehavior.apply({}, arguments), options);
    }
};

$('#car1').mask(carMaskBehavior, spOptions);

Jsbin: https://jsbin.com/zijayiwoxe/edit?html,js,console,output

I am trying just letters, but I do not know how to fix it to define the mask as user input the text to format AAA-9999 or AAAA-9999. How can I do this?

Thank you.


Solution

  • Just change the mask on the fly and allow an optional char to the end:

    var spOptions = {
        onKeyPress: function(val, e, field, options) {
          var mask = "";
    
          if (val.length === 8) {
            mask = 'AAA-AAAAZ'
          } else {
            mask = 'AAAA-AAAA'
          }
          $('#car1').mask(mask, options);
        },
        translation: {
          'Z': {
            pattern: /[.]?/,
            optional: true
          }
        }
      };
    
      $('#car1').mask('AAA-AAAA', spOptions);
    

    Working example