Created
March 13, 2020 17:26
-
-
Save GuilhermeManzano/8d89e683a23b7bc99fd694374ba15d4b to your computer and use it in GitHub Desktop.
Validador de CPF
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Component } from '@angular/core'; | |
import { ModalController, AlertController, NavParams } from '@ionic/angular'; | |
@Component({ | |
selector: 'nota-fiscal', | |
templateUrl: './nota-fiscal.component.html', | |
styleUrls: ['./nota-fiscal.component.scss'], | |
}) | |
export class NotaFiscalComponent { | |
cpf: any; | |
strCPF: any; | |
constructor( | |
private modalController: ModalController, | |
public globalS: GlobalService, | |
private alertController: AlertController, | |
) { } | |
//Exibe uma mensagem de alerta ao usuário, caso o número do CPF seja inválido | |
async myDismiss() { | |
this.cpf = null; | |
await this.modalController.dismiss(this.cpf); | |
} | |
//Função que irá testar se o CPF é valido | |
testaCPF() { | |
var Soma = 0; | |
// Verifica se a variável cpf é igual a "undefined", exibindo uma msg de erro | |
if (this.cpf === undefined) { | |
this.cpfAlert(); | |
return false; | |
} | |
// Esta função retira os caracteres . e - da string do cpf, deixando apenas os números | |
var strCPF = this.cpf.replace('.', '').replace('.', '').replace('-', ''); | |
// Testa as sequencias que possuem todos os dígitos iguais e, se o cpf não tem 11 dígitos, retorna falso e exibe uma msg de erro | |
if (strCPF === '00000000000' || strCPF === '11111111111' || strCPF === '22222222222' || strCPF === '33333333333' || | |
strCPF === '44444444444' || strCPF === '55555555555' || strCPF === '66666666666' || strCPF === '77777777777' || strCPF === '88888888888' || | |
strCPF === '99999999999' || strCPF.length !== 11) { | |
this.cpfAlert(); | |
return false; | |
} | |
// Os seis blocos seguintes de funções vão realizar a validação do CPF propriamente dito, conferindo se o DV bate. Caso alguma das funções não consiga verificar | |
// o DV corretamente, mostrará uma mensagem de erro ao usuário e retornará falso, para que o usário posso digitar novamente um número para ser testado | |
//Multiplica cada digito por numeros de 1 a 9, soma-os e multiplica-os por 10. Depois, divide o resultado encontrado por 11 para encontrar o resto | |
for (let i = 1; i <= 9; i++) { | |
Soma = Soma + parseInt(strCPF.substring(i - 1, i)) * (11 - i); | |
} | |
var Resto = (Soma * 10) % 11; | |
if ((Resto === 10) || (Resto === 11)) { | |
Resto = 0; | |
} | |
if (Resto !== parseInt(strCPF.substring(9, 10))) { | |
this.cpfAlert(); | |
return false; | |
} | |
Soma = 0; | |
for (let k = 1; k <= 10; k++) { | |
Soma = Soma + parseInt(strCPF.substring(k - 1, k)) * (12 - k) | |
} | |
Resto = (Soma * 10) % 11; | |
if ((Resto === 10) || (Resto === 11)) { | |
Resto = 0; | |
} | |
if (Resto !== parseInt(strCPF.substring(10, 11))) { | |
this.cpfAlert(); | |
return false; | |
} | |
//a função this.update() será chamada, caso a validação do Dígito Verificador seja feita com sucesso | |
this.update(); | |
return true; | |
} | |
//Caso o CPF será valido, irá realizar a gravação do mesmo na variável strCPF | |
async update() { | |
await this.modalController.dismiss(this.strCPF); | |
} | |
async cpfAlert() { | |
const alert = await this.alertController.create({ | |
header: 'CPF Inválido!', | |
message: 'Digite um número de CPF válido para prosseguir', | |
buttons: ['OK'] | |
}); | |
await alert.present(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment