0

Please, where I can change this mask function to avoid the user type 0 (zero) as a first number?

This is a mask function to format the input at this format:

(99) 9999-9999 or (99) 99999-9999 

Once here in Brazil the celphone has now 9 digits and normal phones 8 digits. But the city code (between parentheses) could NOT start with 0 (zero), otherwise will mess up the phone number.

// telefone com 9 digitos var SPMaskBehavior = function (val) { return val.replace(/\D/g, '').length === 11 ? '(00) 00000-0000' : '(00) 0000-00009'; }, spOptions = { onKeyPress: function(val, e, field, options) { field.mask(SPMaskBehavior.apply({}, arguments), options); } }; $('#telefone').mask(SPMaskBehavior, spOptions); 

Here's the mask link

4
  • The mask functionality you are using may not support this I would look into adding a regex function that would have [1-9] for the first part of the pattern. Commented Aug 21, 2017 at 0:43
  • Right, i found this reg pattern, but I dont know how to insert this in the mask function LINK REG PATTERN Commented Aug 21, 2017 at 0:54
  • You could put it inside the OnKeypress behavior and then if we regex doesn't match you can return false. I won't use some thing like myRegex.test(val)) Commented Aug 21, 2017 at 0:59
  • Thank you Judson. Problem solved. Commented Aug 21, 2017 at 1:18

1 Answer 1

0

If the first digit entered is a zero...

That is easy to check using a simple if condition.
You just need to check the second character of the value, first is (.

If it is a zero, remove it... And, optionnaly, notify the user.

// telefone com 9 digitos var SPMaskBehavior = function (val) { return val.replace(/\D/g, '').length === 11 ? '(00) 00000-0000' : '(00) 0000-00009'; }, spOptions = { onKeyPress: function(val, e, field, options) { if(field.val()=="(0"){ console.log("NO! No zero to begin."); field.val(field.val().substr(0,1)); // Removes the 0 } field.mask(SPMaskBehavior.apply({}, arguments), options); } }; $('#telefone').mask(SPMaskBehavior, spOptions);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.11/jquery.mask.min.js"></script> <input id="telefone">

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much! Exactly what I need.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.