Alex Zhukovskiy Alex Zhukovskiy - 14 days ago 7
jQuery Question

JQuery advanced input mask to format and mask valid BYTE sequence "10 FE BA 59 6F"

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() {
  $.fn.bitMask = function() {
      var applyMask = function() {
        var maskPattern = 'ZZ ';
        var mask = '';
        var valueToMask = $(this).val();
        var patternRepeatCount = Math.ceil(valueToMask.length / maskPattern.length);
    
        for(var i = 0; i < patternRepeatCount; i++) {
           mask += maskPattern;
        }

        mask += maskPattern;
      
        var option = { translation: {
           'Z': { pattern: /[0-9a-fA-F]/}
        }};
        
        var pseudoElm = $('<input type="text"/>');
        pseudoElm.val(valueToMask);
        pseudoElm.mask(mask, option);
        $(this).val(pseudoElm.val());
    };
    
    $(this).each(function() {
      var self = $(this);
      self.on('keypress', function() {
        setTimeout(applyMask.bind(this), 1);
      });
      
      self.on('paste', function() {
        setTimeout(applyMask.bind(this), 1);
      });
      
    });
  };
    

  $('input').bitMask();
  
});
<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"/>