Brazilian CPF And CNPJ Number Validator - cpfcnpj.js

File Size: 5.6 KB
Views Total: 7026
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   
Brazilian CPF And CNPJ Number Validator - cpfcnpj.js

cpfcnpj.js is a small yet useful jQuery plugin used to validate Brazilian CPF (Cadastro de Pessoas Físicas, Natural Persons Register) and/or CNPJ (Cadastro Nacional da Pessoa Jurídica, National Registry of Legal Entities) numbers with easy.

Thanks to the great jQuery mask plugin, that plugin automatically masks the input into CPF or CNPJ format while typing.

How to use it:

1. Download and place the JavaScript file jquery.cpfcnpj.js after jQuery.

<script src="https://code.jquery.com/jquery-1.12.4.min.js" 
        integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ" 
        crossorigin="anonymous">
</script>
<script src="jquery.cpfcnpj.js"></script>

2. Create a normal text field to accpet the CPF & CNPJ input.

<input type="text" class="validate">

3. Activate the plugin and done. By default, the plugin will validate the CPF and CPFJ numbers when the input loses focus.

$('.validate').cpfcnpj();

4. Customize the trigger event and validate handle.

$('.validate').cpfcnpj({

  // default: focusout
  event: 'click',

  // default: $(this)
  handler: '.btn'
  
});

5. Set the number type to validate.

$('.validate').cpfcnpj({

  // or 'cpf', 'cnpj'
  validate: 'cpfcnpj'

});

6. Enable the input mask functionality on the CPF And CNPJ Number input. Requires jQuery input mask plugin.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.15/jquery.mask.min.js"></script>
$('.validate').cpfcnpj({

  // default: false
  mask: true

});

7. Available callback functions that will be triggered when the CPF or CNPJ Number is valid/invalid.

$('.validate').cpfcnpj({

 ifValid: function (input) { 
   alert('valid') 
  },
 
 ifInvalid: function (input) { 
   alert('invalid') 
  }

});

Changelog:

2019-06-13

  • Updated

2018-08-03

  • Improvement.

This awesome jQuery plugin is developed by gmgomess. For more Advanced Usages, please check the demo page or visit the official website.