1
1
/*
2
- * Copyright 2019 Leonardo Colman Lopes
2
+ * Copyright 2024 Leonardo Colman Lopes
3
3
*
4
4
* Licensed under the Apache License, Version 2.0 (the "License");
5
5
* you may not use this file except in compliance with the License.
14
14
* limitations under the License.
15
15
*/
16
16
@file:Suppress(" MagicNumber" )
17
+
17
18
package br.com.colman.simplecpfvalidator
18
19
19
20
import kotlin.math.abs
@@ -39,7 +40,7 @@ import kotlin.math.abs
39
40
*/
40
41
fun String.isCpf (charactersToIgnore : List <Char > = listOf('.', '-')): Boolean {
41
42
val cleanCpf = this .filterNot { it in charactersToIgnore }
42
- if (cleanCpf.containsInvalidCPFChars() || cleanCpf.isInvalidCpfSize() || cleanCpf.isBlacklistedCpf ()) return false
43
+ if (cleanCpf.containsInvalidCPFChars() || cleanCpf.isInvalidCpfSize() || cleanCpf.isInvalidCpf ()) return false
43
44
return cleanCpf.hasValidVerificationDigits()
44
45
}
45
46
@@ -60,14 +61,14 @@ fun String.isCpf(charactersToIgnore: List<Char> = listOf('.', '-')): Boolean {
60
61
* @see [https://pt.wikipedia.org/wiki/Cadastro_de_pessoas_f%C3%ADsicas]
61
62
* @see [http://normas.receita.fazenda.gov.br/sijut2consulta/link.action?visao=anotado&idAto=1893]
62
63
*/
63
- fun Long.isCpf () : Boolean {
64
+ fun Long.isCpf (): Boolean {
64
65
val absNumber = abs(this )
65
66
return absNumber.toString().isCpf()
66
67
}
67
68
68
69
private fun String.containsInvalidCPFChars () = this .any { ! it.isDigit() }
69
70
private fun String.isInvalidCpfSize () = this .length != 11
70
- private fun String.isBlacklistedCpf () = this in blacklistedCpfs
71
+ private fun String.isInvalidCpf () = this in invalidCpfs
71
72
72
73
// Algorithm from https://www.somatematica.com.br/faq/cpf.php
73
74
private fun String.hasValidVerificationDigits (): Boolean {
@@ -101,7 +102,7 @@ private fun List<Int>.calculateFirstVerificationDigit(): Int {
101
102
val sum = firstNineDigits.withIndex().sumOf { (index, element) -> weights[index] * element }
102
103
103
104
val remainder = sum % 11
104
- return if (remainder < 2 ) 0 else 11 - remainder
105
+ return if (remainder < 2 ) 0 else 11 - remainder
105
106
}
106
107
107
108
private fun List<Int>.calculateSecondVerificationDigit (firstDigit : Int ): Int {
@@ -127,7 +128,11 @@ private fun List<Int>.calculateSecondVerificationDigit(firstDigit: Int): Int {
127
128
return if (remainder < 2 ) 0 else 11 - remainder
128
129
}
129
130
130
- private val blacklistedCpfs = listOf (
131
+ /* *
132
+ * These CPFs although are numerically valid (i.e. [hasValidVerificationDigits] are considered invalid as per CPF
133
+ * specification
134
+ */
135
+ private val invalidCpfs = listOf (
131
136
" 00000000000" ,
132
137
" 11111111111" ,
133
138
" 22222222222" ,
0 commit comments