skip to Main Content

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 🙁

3

Answers


  1. 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.

    Login or Signup to reply.
  2. You can achieve the desired behavior by using a regular expression in the mask option of imask.js. Here’s an updated code snippet that should work for you:

    var phoneMask = IMask(
      document.getElementById('number_phone'), {
        mask: '+{33}0-00000000',
        definitions: {
          '0': {
            validate: function (ch, maskset, pos, strict, opts) {
              // Allow 0 after the country code, but not after the leading 0
              return pos === 3 ? /[0-9]/.test(ch) : /^[1-9]$/.test(ch);
            }
          }
        }
      });
    Login or Signup to reply.
  3. Examples above did not seem to work with useIMask react-hook. This one is a bit simpler and works with the hook also.

    import { useIMask } from 'react-imask'
    
    // ...
    
    const opts = {
      mask: '+{33}#000000000',
      definitions: {
        '#': /^[1-9]{1}$/
      }
    }
    
    const { ref } = useIMask(opts)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search