Nadi Dikun    Interface Mechanics
   About    Contact   

How to validate CPF number using custom method in jQuery.validate plugin

Last week, I polished the subscription process of an app that I’m currently working on for better validation and more friendly UI/UX.

During the subscription this form collects a non-confidential CPF number, which is the Brazilian analog of SIN (Canada) or SSN (USA). This information is critical to be verified upfront, so it’s required to be checked during subscription process, on a client side.

The entire subscription form is being validated by jQuery.Validate plugin, which has many of options for verification, such as digits only, min/max number of characters or even built-in methods for credit card validation.

Certainly, this plugin doesn’t have a built-in method for CPF number validation, since it’s very rarely needed. So I decided to write a custom method for its validation.

To add any custom method into jQuery.validate plugin you need to declare it first right after the DOM is loaded:

 $(document).ready(function() {
   $.validator.addMethod("validateCPF", function (value) {

        // here goes your algorithm code

   }, 'Please provide a valid CPF number');
 });
  1. You have to give your custom method a unique name – “validateCPF” in our case.
  2. You pass some data into the function to validate – “(value)”. In our case, we pass a string that user enters into the input field.
  3. You can provide a default message, which will be shown, in case the data is false – “Please provide a valid CPF number”.
  4. Also, your function has to return true or false to work as a proper custom method inside jQuery.validate plugin.

After you declared this method, it becomes available to be used among other “rules” of the plugin. So you simply add a rule with the name of the plugin, like this:

 $("#subscriptionForm").validate({
   rules: {
     'numCPF': {
       required:  true,
       validateCPF: true
      }
   }
 });

Pretty straightforward, right?

Now, to the CPF number algorithm itself. Different numbers use different algorithms in order to determine if they’re valid or not. That is not a private information, and is being used to avoid accidental typing errors, which are not rare when users deal with long numbers, like social insurance or credit card numbers.

For example, in Canadian SIN number, they use “Luhn algorithm”, which is the same algorithm that is being used for credit card numbers validation. In Brazilian CPF number, the algorithm is different: its last 2 digits serve as “check numbers” to verify the first 9 numbers. You can check out my gist for the CPF number validation:

/*
 * Brazillian CPF number (Cadastrado de Pessoas Físicas) is the equivalent of a Brazilian tax registration number.
 * CPF numbers have 11 digits in total: 9 numbers followed by 2 check numbers that are being used for validation.
 /
$.validator.addMethod("cpfBR", function(value) {
  // Removing special characters from value
  value = value.replace(/([~!@#$%&()_+=`{}[]-|\:;'<>,.\/? ])+/g, "");

// Checking value to have 11 digits only if (value.length !== 11) { return false; }

var sum = 0, firstCN, secondCN, checkResult, i;

firstCN = parseInt(value.substring(9, 10), 10); secondCN = parseInt(value.substring(10, 11), 10);

checkResult = function(sum, cn) { var result = (sum * 10) % 11; if ((result === 10) || (result === 11)) {result = 0;} return (result === cn); };

// Checking for dump data if (value === "" || value === "00000000000" || value === "11111111111" || value === "22222222222" || value === "33333333333" || value === "44444444444" || value === "55555555555" || value === "66666666666" || value === "77777777777" || value === "88888888888" || value === "99999999999" ) { return false; }

// Step 1 - using first Check Number: for ( i = 1; i <= 9; i++ ) { sum = sum + parseInt(value.substring(i - 1, i), 10) * (11 - i); }

// If first Check Number (CN) is valid, move to Step 2 - using second Check Number: if ( checkResult(sum, firstCN) ) { sum = 0; for ( i = 1; i <= 10; i++ ) { sum = sum + parseInt(value.substring(i - 1, i), 10) * (12 - i); } return checkResult(sum, secondCN); } return false;

}, "Please specify a valid CPF number");

As usual, here is a couple of links worth checking:

comments powered by Disqus