1

I have a 'tel' type Input with a telephone pattern (Brazilian number system):

<input class="form-control" maxlength="15" pattern="[\(]?[0-9]{2}[\)]?[ ]?[0-9]{4,5}[-]?[0-9]{4}" type="tel" value="">

I'm also using jQuery Mask Plugin to automatically add the characters I want while typing and retrieve the value without the special characters to store on db. This is my MaskBehavior and options (for the library):

var PhoneMaskBehavior = function (val) {
    return val.replace(/\D/g, '').length === 11 ? '(00) 00000-0000' : '(00) 0000-00009';
},
    phoneOptions = {
        selectOnFocus: true,
        onKeyPress: function(val, e, field, options) {
            field.mask(PhoneMaskBehavior.apply({}, arguments), options);
        }
};

The problem is when I add a default value when loading the number from database. It fills without the special character and I the form doesn't allow submit, as the field is required and out of pattern.

This is what I get when loading a value from db directly in the input:

sample1

This is what I need to match the pattern (and what is inputed when I type the number manually, without loading with the input's value attribute):

enter image description here

Is there a way to automatically load a value and make it match the pattern by adding the special characters between the numbers, without parsing and treating the string?

1
  • Just FYI, you don't need [] around \(, \), and - in that regular expression. Also I'm not familiar with jQuery, but I would guess that you could do what you want with single line of String.prototype.replace. Commented Aug 1, 2019 at 21:31

1 Answer 1

2

Why not apply the mask on load?

var PhoneMaskBehavior = function(val) {
    return val.replace(/\D/g, '').length === 11 ? '(00) 00000-0000' : '(00) 0000-00009';
  },
  phoneOptions = {
    selectOnFocus: true,
    onKeyPress: function(val, e, field, options) {
      field.mask(PhoneMaskBehavior.apply({}, arguments), options);
    }
  };

$(document).ready(function () {
  $('input[type=tel]').mask(PhoneMaskBehavior, phoneOptions)
})
<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.16/jquery.mask.min.js"></script>

<input value="51 3364 7979" type="tel" class="form-control" maxlength="15" pattern="[\(]?[0-9]{2}[\)]?[ ]?[0-9]{4,5}[-]?[0-9]{4}">

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.