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.