Search code examples
javascriptjquerymasking

Mask to complete input


Let's suppose I have the following constants declared:

const begin = '1234';
const end = '789';

and I have one html input with preset value='1234-56??-????-0987'

How can I setup a mask (using jQuery-Mask plugin, or not) to:

  • When the user inserts any number (for example 7) on the input, the value becomes: 1234-567?-????-0987
  • If, after this user inserts '8', it becomes: 1234-5678-????-0987
  • When the user replaces all '?', then stop accepting inputs.
  • If the user backspaces/erases any digit, the corresponding ? appears again.

Currently I have this code:

const start = '123456';
const end = '0987';
const input = document.getElementById('entry-number');
input.addEventListener('input', () => 
{
    const mask = "******";
    const userInput = input.value.replace(/\D/g, "").replace(start, "").replace(end, "");
    const newNumber = start + userInput + mask.slice(userInput.length) + end;
    input.value = newNumber;
});

But

  1. It doesn't respect the mask with hyphens.
  2. If I hit backspace, it completely bugs the input value.

Solution

  • The jQuery inputmask plugin could be used to achieve this.

    We would use the mask 1234-5699-9999-0\\987. The 99-9999 pattern in (approximately) the middle indicates where arbitrary digits may be entered. The \\9 indicates that this position will have a literal "9" and not an arbitrary digit. We can specify ? as the placeholder value which will be used in the absence of any of the arbitrary digits that can be entered.

    $('#entry-number').inputmask({
      mask: '1234-5699-9999-0\\987',
      placeholder: '?'
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.inputmask.min.js"></script>
    <input id="entry-number">