Alex Zhukovskiy Alex Zhukovskiy - 1 year ago 161
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
input value becomes
10 FE BA 59 6F
, i.e. it inserts a space after each byte typed.

How can it be achieved?

Answer Source

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=""></script>
<script src=""></script>
<input type="text"/>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download