mascara and formulary validation

Asked

Viewed 1,606 times

1

I am a beginner in programming, how do I insert a mask and a Cpf validation in this script ? It can be php or jquery.

<h2>Novo Cliente</h2>
<form action="add.php" id = "formCandidate" method="post">
    <hr />
    <div class="row">
        <div class="form-group col-md-7">
            <label for="name">Nome</label>
            <input type="text" class="form-control" id="name" name="candidate['pes_nome']" required>
        </div>
		<div class="row">
        <div class="form-group col-md-3">
            <label for="cpf">CPF</label>
            <input type="text" class="form-control" id="cpf" name="candidate['pes_cpf']" required>
        </div>
    </div>
	<div id="actions" class="row">
        <div class="col-md-12">
            <button type="submit" class="btn btn-primary">Salvar</button>
            <a href="index.php" class="btn btn-default">Cancelar</a>
        </div>
    </div>
</form>	

  • see about jquerymask at this link https://igorescobar.github.io/jQuery-Mask-Plugin/

3 answers

2

If you do not want a plugin to make validations or put masks, you can use the following code:

var mask = '###.###.###-##';
$(document).ready(function() {

  $("#cpf").keypress(function() {
    var tamanho = this.value.length;
    if (event.keyCode < 48 || event.keyCode > 57) {
      event.returnValue = false;
    } else if (tamanho >= 14) {
      event.returnValue = false;
    } else {
      var saida = mask.substring(1, 0);
      var texto = mask.substring(tamanho);
      if (texto.substring(0, 1) != saida) {
        this.value += texto.substring(0, 1);
      }
    }
  });

  $("#cpf").blur(function() {
    cpf = this.value.toString().replace(/\.|\-/g, "");
    if (cpf.length < 11) {
      alert('CPF Invalido! Digite o CPF Completo');
      return;
    }
    var soma1 = 0,
      soma2 = 0,
      vlr = 11;
    for (i = 0; i < 9; i++) {
      soma1 += eval(cpf.charAt(i) * (vlr - 1));
      soma2 += eval(cpf.charAt(i) * vlr);
      vlr--;
    }
    soma1 = (((soma1 * 10) % 11) == 10 ? 0 : ((soma1 * 10) % 11));
    soma2 = (((soma2 + (2 * soma1)) * 10) % 11);

    if (((soma1 * 10) + soma2) != eval(cpf.charAt(9) + cpf.charAt(10)))
      alert('CPF Invalido!');
    else {
      alert('CPF Váido')
    }
  });

});
<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- bootstrap JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<div class="container">
  <h2>Novo Cliente</h2>
  <form action="add.php" id="formCandidate" method="post">
    <hr />
    <div class="row">
      <div class="form-group col-md-7">
        <label for="name">Nome</label>
        <input type="text" class="form-control" id="name" name="candidate['pes_nome']" required>
      </div>
    </div>
    <div class="row">
      <div class="form-group col-md-3">
        <label for="cpf">CPF</label>
        <input type="text" class="form-control" id="cpf" name="candidate['pes_cpf']" required>
      </div>
    </div>
    <div id="actions" class="row">
      <div class="col-md-12">
        <button type="submit" class="btn btn-primary">Salvar</button>
        <a href="index.php" class="btn btn-default">Cancelar</a>
      </div>
    </div>
  </form>
</div>

  • Thanks for the help

2


You can add in input from CPF an attribute pattern (HTML5) that will only allow characters specified in Regex:

// Somente números (`\d`) ponto e hífen e com tamanho de 14 caracteres
pattern="[\d.-]{14}"

Also add to input the attribute maxlength to limit the amount of characters:

maxlength="14"

Soon the input of the CPF will be like this:

<input maxlength="14" pattern="[\d.-]{14}" type="text" class="form-control" id="cpf" name="candidate['pes_cpf']" required>

Note that this check is only on the client side (client-side). It is recommended to perform a validation mainly on server side (server-side, PHP).

Below are all the functions necessary for the functioning. The functions are commented describing the role of each.

// EVENTO KEYUP PARA A MÁSCARA
$("#cpf").on("keyup", function(){
   formataCPF('###.###.###-##', this);
});

// CAPTURA O SUBMIT
$("#formCandidate").on("submit", function(){
   
   var cpf = $("#cpf").val().replace(/[.|-]/g,''); // eliminando ponto e hífen para validação
   
   if( !validaCPF(cpf) ){
      alert("CPF inválido!");
      return false
   }
   
   alert("CPF ok! Formulário será submetido");
});

// FUNÇÃO MÁSCARA
function formataCPF(m,d){
   var i = d.value.length;
   if(i < 14){
      var s = m.substring(0,1);
      var t = m.substring(i);
      if (t.substring(0,1) != s){
         d.value += t.substring(0,1);
      }

      if(i >= 11){
         var c = $("#cpf").val();
         c = c.replace( /\D/g , "");
         c = c.replace( /(\d{3})(\d)/ , "$1.$2");
         c = c.replace( /(\d{3})(\d)/ , "$1.$2");
         c = c.replace( /(\d{3})(\d{1,2})$/ , "$1-$2");
         $("#cpf").val(c);
      }
   }
}

// FUNÇÃO PARA VALIDAR CPF
// CRÉDITO: http://www.geradordecpf.org/funcao-javascript-validar-cpf.html
function validaCPF(cpf){
   var numeros, digitos, soma, i, resultado, digitos_iguais;
   digitos_iguais = 1;
   if(cpf.length < 11) return false;
   for(i = 0; i < cpf.length - 1; i++)
      if(cpf.charAt(i) != cpf.charAt(i + 1)){
         digitos_iguais = 0;
         break;
      }
   if(!digitos_iguais){
      numeros = cpf.substring(0,9);
      digitos = cpf.substring(9);
      soma = 0;
      for(i = 10; i > 1; i--)
         soma += numeros.charAt(10 - i) * i;
         resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
         if(resultado != digitos.charAt(0)) return false;
         numeros = cpf.substring(0,10);
         soma = 0;
         for(i = 11; i > 1; i--)
            soma += numeros.charAt(11 - i) * i;
            resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
            if(resultado != digitos.charAt(1)) return false;
      return true;
   }else return false;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Novo Cliente</h2>
<form action="add.php" id = "formCandidate" method="post">
    <hr />
    <div class="row">
        <div class="form-group col-md-7">
            <label for="name">Nome</label>
            <input type="text" class="form-control" id="name" name="candidate['pes_nome']" required>
        </div>
		<div class="row">
        <div class="form-group col-md-3">
            <label for="cpf">CPF</label>
            <input maxlength="14" pattern="[\d.-]{14}" type="text" class="form-control" id="cpf" name="candidate['pes_cpf']" required>
        </div>
    </div>
	<div id="actions" class="row">
        <div class="col-md-12">
            <button type="submit" class="btn btn-primary">Salvar</button>
            <a href="index.php" class="btn btn-default">Cancelar</a>
        </div>
    </div>
</form>

  • Thank you very much for your help, you solved the problem. Even forgot to comment on the question, but the solution I was looking for was a backend and not frontend.

1

Example : http://jsfiddle.net/5wkjbu8c/

HTML

<form id="meuForm" action="">
   <label>CPF</label>
   <input id="cpf" name="cpf" type="text" value="" /><br />
   <input type="submit" value="Enviar" />
</form>

Jquery:

 jQuery.validator.addMethod("cpf", function(value, element) {
       value = jQuery.trim(value);

        value = value.replace('.','');
        value = value.replace('.','');
        cpf = value.replace('-','');
        while(cpf.length < 11) cpf = "0"+ cpf;
        var expReg = /^0+$|^1+$|^2+$|^3+$|^4+$|^5+$|^6+$|^7+$|^8+$|^9+$/;
        var a = [];
        var b = new Number;
        var c = 11;
        for (i=0; i<11; i++){
            a[i] = cpf.charAt(i);
            if (i < 9) b += (a[i] * --c);
        }
        if ((x = b % 11) < 2) { a[9] = 0 } else { a[9] = 11-x }
        b = 0;
        c = 11;
        for (y=0; y<10; y++) b += (a[y] * c--);
        if ((x = b % 11) < 2) { a[10] = 0; } else { a[10] = 11-x; }

        var retorno = true;
        if ((cpf.charAt(9) != a[9]) || (cpf.charAt(10) != a[10]) || cpf.match(expReg)) retorno = false;

        return this.optional(element) || retorno;

    }, "Informe um CPF válido");


    $(document).ready(function(){

       $("#meuForm").validate({
          rules: {
              cpf: {cpf: true, required: true}
          },
          messages: {
             cpf: { cpf: 'CPF inválido'}
          }
          ,submitHandler:function(form) {
             alert('ok');
          }
       });
    });

This plugin is very good : jQuery-CPF-CNPJ-Validator-plugin

$(document).ready(function () {

$('#cpf').cpfcnpj({ mask: true, validate: 'cpfcnpj', event: 'click', handler: '.btn', ifValid: 

function (input) {
  input.removeClass("error"); }, ifInvalid: (input) { input.addClass("error"); 
     } 
  });

}); 

Masking : http://igorescobar.github.io/jQuery-Mask-Plugin/docs.html

$(document).ready(function(){
  $('#cpf').mask('000.000.000-00');
});
  • Thanks for the help

Browser other questions tagged

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