Using jQuery Validation Engine and CPF validation

4

I'm using the jQuery Validation Engine with translations file for Portuguese. I have added the following line to the JavaScript:

"cpf": {
    "regex": /^\d{2}\.\d{3}\.\d{3}\/\d{4}\-\d{2}$/,
     "alertText": "* CPF inválido"
 }
  
Class="validate[required,custom[cpf]]

But this validation is not very efficient, since it only checks the number of characters.

How can I make a method to validate the CPF and continue using Validation Engine in this way?

    
asked by anonymous 16.12.2014 / 01:38

5 answers

3

CPF validation occurs through the implementation of an algorithm.

With ERs it might even be possible through the modern metaphor (? {code}} , but I find it quite improbable, in addition to plastering your Application.

The best thing to do is to add a new validator.

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');
      }
   });
});

Example on JSFiddle

    
16.12.2014 / 02:29
3

Very simple function removed from link To use, simply send the numeric value of the CPF.

function validarCPF(input_cpf){
 //get input
 if(input_cpf){
   var input=input_cpf.toString();

   var numeros=[];
   var pesos_A=[10,9,8,7,6,5,4,3,2];
   var pesos_B=[11,10,9,8,7,6,5,4,3,2];
   var sum=0;
   var x1=0;
   var x2=0;

   for(var i=0;i=2){
     x1=11-mod;
   }

   //calcula digito 2
   sum=0;
   for(var i=0;i=2){
     x2=11-mod;
   }

   if(x1==input[9] && x2==input[10]){
     return true;
   }else{
     return false;
   }
   }else{
     return false;
   }
};
    
08.06.2015 / 04:59
3

In the HTML insert the "id" of the CPF input field of "cpf" and add the script below. When the CPF field loses focus the function below will be executed:

<script type="text/javascript">
$(function()
{
    //Executa a requisição quando o campo username perder o foco
    $('#cpf').blur(function()
    {
        var cpf = $('#cpf').val().replace(/[^0-9]/g, '').toString();

        if( cpf.length == 11 )
        {
            var v = [];

            //Calcula o primeiro dígito de verificação.
            v[0] = 1 * cpf[0] + 2 * cpf[1] + 3 * cpf[2];
            v[0] += 4 * cpf[3] + 5 * cpf[4] + 6 * cpf[5];
            v[0] += 7 * cpf[6] + 8 * cpf[7] + 9 * cpf[8];
            v[0] = v[0] % 11;
            v[0] = v[0] % 10;

            //Calcula o segundo dígito de verificação.
            v[1] = 1 * cpf[1] + 2 * cpf[2] + 3 * cpf[3];
            v[1] += 4 * cpf[4] + 5 * cpf[5] + 6 * cpf[6];
            v[1] += 7 * cpf[7] + 8 * cpf[8] + 9 * v[0];
            v[1] = v[1] % 11;
            v[1] = v[1] % 10;

            //Retorna Verdadeiro se os dígitos de verificação são os esperados.
            if ( (v[0] != cpf[9]) || (v[1] != cpf[10]) )
            {
                alert('CPF inválido: ' + cpf);

                $('#cpf').val('');
                $('#cpf').focus();
            }
        }
        else
        {
            alert('CPF inválido:' + cpf);

            $('#cpf').val('');
            $('#cpf').focus();
        }
    });
});

    
30.05.2016 / 02:55
1

Using the jQuery Validation Engine there is a rule called remote , which:

  

[...] performs a remote check with the url and the value entered in the field, so if the response to the validation request is false, then Validation understands that the information in the field is not valid, now if the answer is true then the information is valid. For example: check if CFP already exists in the application;

Source : Validation with jQuery

I hope I have helped;)

    
16.12.2016 / 15:01
0

Try using a custom checker with a function:

"cpf": {
       "func": function(field, rules, i, options) {
            var regex = /^\d{2}\.\d{3}\.\d{3}\/\d{4}\-\d{2}$/;
            if (!regex.test(field.val())
                return false;

            // outras verificações, tais como:
            //  - dígitos verificadores

            return true;
       },
       "alertText": "CPF inválido"
},
    
16.12.2014 / 02:27