Search code examples
angularmasksweetalert2

Number mask in SweetAlert2


I would like to put a number mask in an input of sweetalert2, can you help me? my code:

onClick(btn) {
    let code2_fa = '';
    if (JSON.parse(localStorage.getItem('user')).password.two_factors.is_active) {
      swal({
        title: 'Digite o TOKEN para prosseguir',
        imageUrl: './assets/imgs/Authy.svg',
        imageAlt: 'Logo Authy',
        input: 'text',
        inputPlaceholder: 'Digite o TOKEN...',
        inputAttributes: {
          maxlength: '6',
          autofocus: 'true',
          required: 'true',
        },
        inputValue: code2_fa,
        animation: true,
        allowEnterKey: true,
        inputAutoTrim: true,

      })
  }

I am using Angular 6, the intention is to display a modal so that the user can enter their authy code.


Solution

  • If you want to use vanilla javascript, you could use the onBeforeOpen property of swal to register an handler for key press events on the input, e.g.:

    onBeforeOpen: () => {
      swal.getInput().onkeypress = (event) => {
        return Number.isInteger(parseInt(event.key))
      }
    }
    

    The above implementation is a very simple key press detector that returns false if the key pressed is not a number.

    A running implementation of that can be seen at https://three-keeper.glitch.me/