Alex Zhukovskiy Alex Zhukovskiy - 21 days ago 5
jQuery Question

jQuery mask to input byte sequence

I'm trying to implement masked input which allows to input bytes, for example

10 FE BA 59 6F
, I'm trying to do it like this:

$(function() {
$('input').mask("ZZ", {
translation: {
Z: { pattern: /[0-9a-fA-F]{1,2}\s*/, optional: true, recursive: true}
},
maxlength: false
});
});


But it just doesn't allow to type anything.

What do I want: when user writes
10FEBA596F
input value becomes
10 FE BA 59 6F
, i.e. it inserts a space after each byte typed.

How can it be achieved?

Answer

Please have a look below for the byte mask you requested.

As the masking translation pattern won't support inserting a space and no recursive masking pattern supported there at the moment, I have to override the keypress event in the masking options to achieve this.

$(function() {
  var options =  {onKeyPress: function(cep, e, field, options){
    var maskPattern = 'ZZ ';
    var mask = '';
    var patternRepeatCount = Math.ceil(cep.length / maskPattern.length);
    
    for(var i = 0; i < patternRepeatCount; i++) {
       mask += maskPattern;
    }
    
    mask += maskPattern; // Add 1 extra to let to type another one after a space
    $('input').mask(mask, options);
}, translation: {
      'Z': { pattern: /[0-9a-fA-F]/}
    }};

$('input').mask('ZZ ', options);
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://igorescobar.github.io/jQuery-Mask-Plugin/js/jquery.mask.min.js"></script>
<input type="text"/>

Comments