How to mask an input in HTML5?

5

For example ... I want a input unique for phone numbers. When typing the DDD it automatically receives the parentheses: (xx). When typing the rest of the numbers it splits with a hyphen, for example: (xx) abcd-efgh. And in the cases of states that received the ninth digit, (xx) 9abcd-efgh.

How can I do this?

    
asked by anonymous 18.02.2015 / 17:33

2 answers

6

You can mask a field using:

  

JQuery Mask Plugin
Documentation

Usage example:

$(document).ready(function(){
    $('#telefone').mask('(00) 0000-0000');
});

Or in the html itself:

<input type="text" name="telefone" data-mask="(00) 0000-0000" data-mask-selectonfocus="true" />

You can also apply callback, finally ... there are several examples in the documentation that fit your need ..

  

For cases where the state has the ninth digit, you can use the   On-the-fly change: Example removed from documentation , you only need   the adaptation to your need:

var options =  {onKeyPress: function(cep, e, field, options){
  var masks = ['00000-000', '0-00-00-00'];
    mask = (cep.length>7) ? masks[1] : masks[0];
  $('.crazy_cep').mask(mask, options);
}};

$('.crazy_cep').mask('00000-000', options);

Or the solution that @Wallace provided in the comments that would look like this:

$(document).ready(function(){
    $('#telefone').mask('(00) 0000-0000#');
});

Or also the following expression:

$(document).ready(function(){
    $('#telefone').mask('(00) 0000-00009');
});

Where 0 would be mandatory and optional 9;

@Wallace also cited validation using HTML5.

    
18.02.2015 / 17:40
4

What you're looking for can be done easily with jQuery Mask .

Its use happens exactly as @RafaelWithoeft describes in your answer.

$(document).ready(function(){
    $('[name=telefone]').mask('(00) 0000-0000');
});

As for doing this with HTML5 only, what you will be able to do at most is to use the pattern attribute. However this attribute will not serve for self-completion, but only for the field validation according to the desired format.

For example, in the case of a phone validation:

<input type="text" pattern="\(\d{2}\)\d{4}-\d{4}" />
#exige que o campo seja preenchido com "(99)9999-9999"
    
18.02.2015 / 17:43