Skip to content

Instantly share code, notes, and snippets.

@rmpt
Last active January 20, 2023 12:26
Show Gist options
  • Save rmpt/2ba7fb2ec190e433fce4a9eefb62fdf7 to your computer and use it in GitHub Desktop.
Save rmpt/2ba7fb2ec190e433fce4a9eefb62fdf7 to your computer and use it in GitHub Desktop.
Kotlin NIF validator - validador de número de contribuinte
object NifValidator {
private val validationSet1 = listOf("1", "2", "3", "5", "6", "8")
private val validationSet2 = listOf("45", "70", "71", "72", "74", "75", "77", "79", "90", "91", "98", "99")
fun isValid(
nif: String
): Boolean {
if (nif.length != 9) {
return false
}
if (!validationSet1.contains(nif.substring(0, 1)) && !validationSet2.contains(nif.substring(0, 2))) {
return false
}
val nifNumbers = nif.map{ it.toString().toInt() }
val total =
nifNumbers[0] * 9 +
nifNumbers[1] * 8 +
nifNumbers[2] * 7 +
nifNumbers[3] * 6 +
nifNumbers[4] * 5 +
nifNumbers[5] * 4 +
nifNumbers[6] * 3 +
nifNumbers[7] * 2;
val module11 = (total % 11)
val checkDigit = if(module11 < 2) 0 else 11 - module11
return checkDigit == nifNumbers[8]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment