javascriptvalidationinputimaskjs

Remove "0" at the begininning of phone number with imask.js


I'm trying to use imask.js for phone validating on subscribe form.

I currently have this simple code :

var phoneMask = IMask(
document.getElementById('number_phone'), {
    mask: '+{33}000000000'
});

I want to disable the capacity of put a 0 just after the {33} to have this kind of number at the end of the subscription : +33666666666. But allow to put a 0 after the first number.

I've try some Regex but still not working :(


Solution

  • Instead of using a single mask for the whole phone number, we break it into three parts:

    const phoneMask = IMask(document.getElementById('number_phone'), {
      mask: [
        {
          mask: '+33',
        },
        {
          mask: '9{0}',
          definitions: {
            '9': {
              validator: '[1-9]',
              cardinality: 1,
            },
          },
        },
        {
          mask: '00000000',
        },
      ],
    });
    

    What the masks does:

    1. The prefix +33 is always present.
    2. The first digit after the prefix, which cannot be a 0. We use a custom definition to only allow digits from 1 to 9.
    3. The rest of the phone number, which allows any digits (including 0).

    The mask will prevent the user from entering a 0 immediately after the +33 country code but will allow entering a 0 after the first digit.