Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

199
Views
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>

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!