Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- _validateField () {
- // Esconde o teclado
- Keyboard.dismiss()
- if (this.state.cpfCnpj && this.state.cpfCnpj.length === 11 && this._validateCPF()) {
- // Verifica se o campo de CNPJ esta preenchido
- // Verifica se o campo de CPF tem o mínimo de caracteres de um CPF
- // Valida se o CPF é válido
- this._handleLogin()
- } else if (this.state.cpfCnpj && this.state.cpfCnpj.length === 14 && this._validateCNPJ()) {
- // Verifica se o campo de CNPJ esta preenchido
- // Verifica se o campo de CNPJ tem o mínimo de caracteres de um CNPJ
- // Valida se o CNPJ é válido
- this._handleLogin()
- } else {
- this._toastError('CPF/CNPJ Inválido')
- }
- }
- _validateCPF() {
- // Função para validar o CPF
- // Inspirado em: www.receita.fazenda.gov.br/aplicacoes/atcta/cpf/funcoes.js
- const strCPF = this.state.cpfCnpj
- let Soma;
- let Resto;
- Soma = 0;
- if (!strCPF.length === 14) {
- this._toastError('CPF Inválido')
- return false
- }
- for (i = 1; i <= 9; i++) {
- Soma = Soma + parseInt(strCPF.substring(i - 1, i)) * (11 - i);
- Resto = (Soma * 10) % 11;
- }
- if ((Resto === 10) || (Resto === 11)) {
- Resto = 0
- }
- if (Resto != parseInt(strCPF.substring(9, 10))) {
- this._toastError('CPF Inválido')
- return false
- }
- Soma = 0;
- for (i = 1; i <= 10; i++) {
- Soma = Soma + parseInt(strCPF.substring(i - 1, i)) * (12 - i);
- Resto = (Soma * 10) % 11;
- }
- if ((Resto === 10) || (Resto === 11)) {
- Resto = 0;
- }
- if (Resto != parseInt(strCPF.substring(10, 11))) {
- this._toastError('CPF Inválido')
- return false
- }
- return true
- }
- _validateCNPJ() {
- // Função para validar o CNPJ
- // Inspirado em: http://www.geradorcnpj.com/javascript-validar-cnpj.htm
- const cnpj = this.state.cpfCnpj.replace(/[^\d]+/g,'')
- if(!cnpj.length === 14) {
- this._toastError('CPF Inválido')
- return false
- }
- let tamanho = cnpj.length - 2
- let numeros = cnpj.substring(0,tamanho)
- let digitos = cnpj.substring(tamanho)
- let soma = 0
- let pos = tamanho - 7
- for (i = tamanho; i >= 1; i--) {
- soma += numeros.charAt(tamanho - i) * pos--
- if (pos < 2) {
- pos = 9
- }
- }
- resultado = soma % 11 < 2 ? 0 : 11 - soma % 11
- if (resultado != digitos.charAt(0)) {
- this._toastError('CPF Inválido')
- return false
- }
- tamanho = tamanho + 1
- numeros = cnpj.substring(0,tamanho)
- soma = 0
- pos = tamanho - 7
- for (i = tamanho; i >= 1; i--) {
- soma += numeros.charAt(tamanho - i) * pos--;
- if (pos < 2) {
- pos = 9
- }
- }
- resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
- if (resultado != digitos.charAt(1)) {
- this._toastError('CPF Inválido')
- return false
- }
- return true
- }
Advertisement
Add Comment
Please, Sign In to add comment