javascriptjqueryhtmljquery-mask

Automatically format value before inserting into input with pattern


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?


Solution

  • 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}">