Emmanuel Lima
Emmanuel Lima

Reputation: 21

Input mask and first keypress

I'm using a jQuery plugin to build an input mask with a predefined country code starting on +55.

It's working with all numbers, except for the number 5. That's the problem.

When the first number typed is 5, the output should be: +55 (5

But it doesn't.

Can I use keydown or keypress to fix this? I don't know how to do this.

https://jsfiddle.net/xyt76hLw/

let $phoneError = $('#phoneerror');
let phoneMask = function(val) {
  return '+55 (00) 0 0000-0000'
};
let avoidZero = {
  onKeyPress: function(val, e, field, options) {
$phoneError.text('');

if (val == "+55 (0") {
  $phoneError.text("don't start with zero");
  field.val((i, v) => v.substr(0, 1));
}
field.mask(phoneMask.apply({}, arguments), options)
  }
};

$("input[type='tel']").mask(phoneMask, avoidZero)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.11/jquery.mask.min.js"></script>

<input pattern=".{20,}" id="phone1" name="phone1" placeholder="your phone" type="tel" />
<div id="phoneerror" style="color: #333; font-size: 14px; padding-top: 2px;"></div>

Upvotes: 0

Views: 1088

Answers (1)

slashroot
slashroot

Reputation: 753

There seems to be an issue with that mask lib when starting the mask with hardcoded numbers ie +55 (00)... and then entering the first digit as 5, for some reason it doesnt trigger the mask. But you can get away with something like this.

let $phoneError = $('#phoneerror');
$('#phone1').mask("+55 (00) 0 0000-0000");

$('#phone1').on('input propertychange paste', function (e) {
    var val = $(this).val();
    if(val == "+5") {
        $(this).val("+55 (5");
    }
    if(val == "+55 (0") {
        $(this).val("+55 (");
      $phoneError.text("don't start with zero");
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.11/jquery.mask.min.js"></script>

<input pattern=".{20,}" id="phone1" name="phone1" placeholder="your phone" type="tel" />
<div id="phoneerror" style="color: #333; font-size: 14px; padding-top: 2px;"></div>

Upvotes: 1

Related Questions