Using jQuery Validation Engine and CPF validation

Asked

Viewed 24,461 times

5

I am using jQuery Validation Engine with translation file for English. I added the following line to Javascript:

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

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

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

5 answers

5

CPF validation occurs through the implementation of an algorithm.

With Ers it may even be possible through the modern metacharacter (?{code}), but I find it quite unlikely 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 in Jsfiddle

  • 1

    I did not use the built-in snippet because it is giving an error in the console, tomorrow I see what can be. And as for the algorithm, I picked up a random one on the Internet, didn’t get to optimize.

  • Oh yes, but I already have more than 10 "obsolete" in the list :) - Although the current hat I think was tailor-made for my "avatar".

  • I had some problems on the console, such as "Cannot read Property 'call' of Undefined. Exception ocurred when checking element", but I decided to declare the variables. var Cpf = value.replace('-','); (add the var), and added the lines below " var c": var i; var x; var y;

3

In HTML put 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();
        }
    });
});

3

Very simple function removed from http://geradorderg.com/logica-verificador-de-cpf/ To use, just 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;
   }
};

1

Using the jQuery Validation Engine there is a rule (Rule) called remote, that:

[...] perform a remote check with the url and with 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’ve helped ;)

0

Try using a custom checker with 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"
},

Browser other questions tagged

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