Mask in html and css form only

Asked

Viewed 9,708 times

1

I’m starting in HTML/CSS and trying to create mask only in these markings (HTML/CSS) for my form fields. It will be possible or should use Javascript for the import of masks?

<label for="campo3">Data de Nascimento</label>
<input id="campo3" type="text" class="form-control" placeholder="Ex.: dd/mm/aaaa" data-mask="00/00/0000" maxlength="8" autocomplete="off" name="customer['birthdate']">

  • you can use type="date" and HTML makes a mask and validation

  • @Guilhermecostamilam The problem with type="date" is that it doesn’t have support in IE. It seems to me also that it will want to use other masks without being of dates.

  • Mascara I don’t think CSS does, actually I’m sure. What you can do is use the Type correctly and make Patterns to validate the field with Required. But with the mask, the most you can do is use the Placeholder... At least as far as I know

  • In addition to "date", what types of mask you will need?

  • these scripts should be run in header or footer ? or siste js folder ?

Show 1 more comment

4 answers

2


For fields where "dates" will be, you could use the attribute type="date", but it has no support in Internet Explorer and Safari, according to documentation on MDN.

Only with CSS/HTML you will not be able to create masks in the fields. This type of manipulation is only possible through script. The placeholder is only indicated to illustrate to the user the format or type of data to be entered.

There are some plugins of mask that you can import, but you can implement with pure Javascript without the need to import anything. See a simple Javascript function that formats the data entered according to the type reported in oninput:

function mascara(i,t){

   var v = i.value;

   if(isNaN(v[v.length-1])){
      i.value = v.substring(0, v.length-1);
      return;
   }

   if(t == "data"){
      i.setAttribute("maxlength", "10");
      if (v.length == 2 || v.length == 5) i.value += "/";
   }

   if(t == "cpf"){
      i.setAttribute("maxlength", "14");
      if (v.length == 3 || v.length == 7) i.value += ".";
      if (v.length == 11) i.value += "-";
   }

   if(t == "cnpj"){
      i.setAttribute("maxlength", "18");
      if (v.length == 2 || v.length == 6) i.value += ".";
      if (v.length == 10) i.value += "/";
      if (v.length == 15) i.value += "-";
   }
}

The part below prevents the insertion of another character type other than number:

if(isNaN(v[v.length-1])){
   i.value = v.substring(0, v.length-1);
   return;
}

At the event oninput you send to the function the element and the data type to be formatted:

oninput="mascara(this, 'data')"
oninput="mascara(this, 'cpf')"
oninput="mascara(this, 'cnpj')"

And the function itself already delimits the number of characters that will be allowed in the field:

i.setAttribute("maxlength", "14"); // para CPF

See in operation:

function mascara(i,t){
   
   var v = i.value;
   
   if(isNaN(v[v.length-1])){
      i.value = v.substring(0, v.length-1);
      return;
   }
   
   if(t == "data"){
      i.setAttribute("maxlength", "10");
      if (v.length == 2 || v.length == 5) i.value += "/";
   }

   if(t == "cpf"){
      i.setAttribute("maxlength", "14");
      if (v.length == 3 || v.length == 7) i.value += ".";
      if (v.length == 11) i.value += "-";
   }

   if(t == "cnpj"){
      i.setAttribute("maxlength", "18");
      if (v.length == 2 || v.length == 6) i.value += ".";
      if (v.length == 10) i.value += "/";
      if (v.length == 15) i.value += "-";
   }

   if(t == "cep"){
      i.setAttribute("maxlength", "9");
      if (v.length == 5) i.value += "-";
   }

   if(t == "tel"){
      if(v[0] == 9){
         i.setAttribute("maxlength", "10");
         if (v.length == 5) i.value += "-";
      }else{
         i.setAttribute("maxlength", "9");
         if (v.length == 4) i.value += "-";
      }
   }
}
<label for="campo3">Data de Nascimento</label>
<input oninput="mascara(this, 'data')" id="campo3" type="text" class="form-control" placeholder="Ex.: dd/mm/aaaa" autocomplete="off" name="customer['birthdate']">
<br>
<label for="campo4">CPF</label>
<input oninput="mascara(this, 'cpf')" id="campo4" type="text" class="form-control" placeholder="Ex.: xxx.xxx.xxx-xx" autocomplete="off" name="customer['cpf']">
<br>
<label for="campo5">CNPJ</label>
<input oninput="mascara(this, 'cnpj')" id="campo5" type="text" class="form-control" placeholder="Ex.: xx.xxx.xxx/xxxx-xx" autocomplete="off" name="customer['cnpj']">
<br>
<label for="campo6">CEP</label>
<input oninput="mascara(this, 'cep')" id="campo6" type="text" class="form-control" placeholder="Ex.: xxxxx-xxx" autocomplete="off" name="customer['cep']">
<br>
<label for="campo7">Telefone</label>
<input oninput="mascara(this, 'tel')" id="campo7" type="text" class="form-control" placeholder="Ex.: xxxxx-xxxx" autocomplete="off" name="customer['tel']">

  • Thank you very much for the perfect explanation. Just a very ignorant question, all this script I put together with html in the Forms or create a separate scritp with the function? Thank you.

  • Vc puts between <script></script tags>

  • Thanks friend. How would I look if I wanted to put masks for zip code and phone/cell phone? Abcs.

  • I’ll do it here and include it in the answer... just a moment

  • Thank you! I don’t even know how to thank you. Abcs

  • Updated answer. QQ problem may warn.

  • If anyone wants DDD, I made the change

Show 2 more comments

0

<!DOCTYPE html>
<html lang="pt-br">
 <head>
  <title>Kaio Maravilhoso</title>
  <meta charset = "UTF-8"/>
  <link rel ="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
 integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
  <script>
   function mascaraData(){

   var data = document.getElementById('txtData').value;
   if(data.length==2){
    document.getElementById('txtData').value = data +'/';
     }
   else if (data.length==5){
    document.getElementById('txtData').value = data +'/';
   }
}

   function mascaraRg(){

   var rg= document.getElementById('txtRg').value;
   if(rg.length==2){
    document.getElementById('txtRg').value = rg +'.';
     }
   else if (rg.length==6){
    document.getElementById('txtRg').value = rg +'.';
   }
   else if (rg.length==9){
    document.getElementById('txtRg').value = rg +'-';
   }
}

   function mascaraTelefone(){

   var telefone= document.getElementById('txtTelefone').value;
   if(telefone.length==1){
    document.getElementById('txtTelefone').value ='(' + telefone;
     }
   else if (telefone.length==3){
    document.getElementById('txtTelefone').value = telefone +')';
   }

   else if (telefone.length==8){
    document.getElementById('txtTelefone').value = telefone +'-';
   }
}

   function mascaraCel(){

   var celular= document.getElementById('txtCel').value;
   if(celular.length==1){
    document.getElementById('txtCel').value ='(' + celular;
     }
   else if (celular.length==3){
    document.getElementById('txtCel').value = celular +')';
   }
   else if (celular.length==9){
    document.getElementById('txtCel').value = celular +'-';
   }
}




   function mascaraCpf(){
   var cpf = document.getElementById('txtCpf').value;
    if(cpf.length==3){
     document.getElementById('txtCpf').value = cpf +'.';
}
    else if(cpf.length==7){
     document.getElementById('txtCpf').value = cpf +'.';
}
    else if (cpf.length==11){
     document.getElementById('txtCpf').value = cpf +'-';
}    
}  

function checarEmail(){

   var email= document.getElementById('txtEmail').value;
   if(email==""||email.indexOf('@')==-1||email.indexOf('.')==-1){

    alert("Por favor Insira um E-mail valido");

}
}

function limpa_formulário_cep() {

            document.getElementById('txtRua').value=("");
            document.getElementById('txtBairro').value=("");
            document.getElementById('txtCidade').value=("");
            document.getElementById('txtUf').value=("");
    }
 function meu_callback(conteudo) {
        if (!("erro" in conteudo)) {
            //Atualiza os campos com os valores.
            document.getElementById('txtRua').value=(conteudo.logradouro);
            document.getElementById('txtBairro').value=(conteudo.bairro);
            document.getElementById('txtCidade').value=(conteudo.localidade);
            document.getElementById('txtUf').value=(conteudo.uf);

        } 
        else {

            limpa_formulário_cep();
            alert("CEP não encontrado.");
        }
    }

 function mascaraCep(){
   var cep = document.getElementById('txtCep').value;
    if(cep.length==5){
     document.getElementById('txtCep').value = cep +'-';
}
}
 function pesquisacep(valor) {


        var cep = valor.replace(/\D/g, '');


        if (cep != "") {


            var validacep = /^[0-9]{8}$/;


            if(validacep.test(cep)) {

                //Preenche os campos com "..." enquanto consulta webservice.
                document.getElementById('txtRua').value="...";
                document.getElementById('txtBairro').value="...";
                document.getElementById('txtCidade').value="...";
                document.getElementById('txtUf').value="...";



                var script = document.createElement('script');


                script.src = 'https://viacep.com.br/ws/'+ cep + '/json/?callback=meu_callback';


                document.body.appendChild(script);

            } 
            else {

                limpa_formulário_cep();
                alert("Formato de CEP inválido.");
            }
        }
        else {

            limpa_formulário_cep();
        }
    };
  </script>
 </head>
 <body>
 <div class="container">
  <h1>Cadastro</h1>
  <hr />


  <form method="get class "form-group">

  <div class="row">


  <div class ="col-md-6">
   <div class="form-group">
    Nome:<input type="text" class= "form-control" id="txtNome"  maxlength="10"/> 
  </div>
  <div class = "row">
  <div class ="col-md-4">
   <div class="form-group">
    Data:<input type="text" class= "form-control" id="txtData" onkeypress="mascaraData()" maxlength="10"/> 
  </div>
</div>
</div>
  <div class="row">
  <div class ="col-md-6">
  <div class="form-group">
    CPF:<input type="text" class= "form-control" id ="txtCpf" onkeypress="mascaraCpf()" maxlength="14"/>

  </div>
  </div>
  <div class ="col-md-6">
  <div class="form-group">
    RG:<input type="text" class= "form-control" id ="txtRg" onkeypress="mascaraRg()" maxlength="12"/>
  </div>
  </div>
  </div>
  <div class="form-group">
    Telefone:<input type="text" class= "form-control" id ="txtTelefone" onkeypress="mascaraTelefone()" maxlength="13"/>
  </div>

  <div class="form-group">
    Celular:<input type="text" class= "form-control" id ="txtCel" onkeypress="mascaraCel()" maxlength="14"/>
  </div>

<div class="form-group">
    Cep:<input type="text" class= "form-control" id ="txtCep" onblur="pesquisacep(this.value)" onkeypress="mascaraCep()"/>
  </div>

<div class="form-group">
    Cidade:<input type="text" class= "form-control" id ="txtCidade"/>
  </div>

<div class="form-group">
    Bairro:<input type="text" class= "form-control" id ="txtBairro"/>
  </div>

<div class="form-group">
    Rua:<input type="text" class= "form-control" id ="txtRua"/>
  </div>

<div class="form-group">
    Uf:<input type="text" class= "form-control" id ="txtUf"/>
  </div>

  <div class="form-group">
    Email:<input type="text" class= "form-control" id ="txtEmail" onblur="checarEmail();"/>
  </div>

  <div class="form-group">
   Selecione
   <select class ="form-control">
    <option></option>
    <option>opção 1</option>
    <option>opção 2</option>
    <option>opção 3</option>
    <option>opção 4</option>
   </select>
  </div>

  <input type="button" class="btn btn-primary"
  value="enviar"/>
  </div>
  <div class="col-md-6">
  </div>
</div>

</form>
</div>
</body>
</html>
  • 1

    It would be interesting to include a brief description of your approach.

0

If anyone wants the mask with DDD (xx) xxxx-xxxx:

if(t === "tel"){
  if (v.length === 1) i.value = "(" + i.value;
  if (v.length === 3) i.value += ") ";
  if(v[5] == 9){
     i.setAttribute("maxlength", "15");
     if (v.length === 10) i.value += "-";
  }else{
     i.setAttribute("maxlength", "14");
     if (v.length === 9) i.value += "-";
  }
}

0

If anyone wants, I made this mask for CPF with few javascript lines. The attribute onkeypress="return event.charCode >= 48 && event.charCode <= 57" direct in the html field is which allows only numbers.

The eventListener "input" returns the validations whenever a number is entered in the field.

window.addEventListener('load', () => {
        let a = document.getElementById('campo');
        
        a.addEventListener("input", () => {
            let arr = a.value.split('');
            
            if(arr.length > 3 && arr[3] != "."){
                arr.splice(3,0,'.');
            }

            if(arr.length > 7 && arr[7] != "."){
                arr.splice(7,0,'.');
            }

            if(arr.length > 11 && arr[11] != "-"){
                arr.splice(11,0,'-');
            }

            a.value = arr.join('');
        });
    });
 <input type="text" onkeypress="return event.charCode >= 48 && event.charCode <= 57" maxlength="14" name="" placeholder="Máscara CPF" id="campo">

Browser other questions tagged

You are not signed in. Login or sign up in order to post.