|
| 1 | +package no.nav.emottak.utils.person |
| 2 | + |
| 3 | +// Based on fnrValideringUtil.ts from https://github.com/navikt/finnfastlege |
| 4 | +abstract class PidValidator { |
| 5 | + |
| 6 | + companion object { |
| 7 | + |
| 8 | + fun isValidFodselsnummer(fodselsnummer: String): Boolean { |
| 9 | + if (!fodselsnummer.matches(Regex("^[0-9]{11}\$"))) { |
| 10 | + return false |
| 11 | + } |
| 12 | + if (!isValidFodselsdato(fodselsnummer.substring(0, 6))) { |
| 13 | + return false |
| 14 | + } |
| 15 | + val fodselsnummerListe = fodselsnummer.map { it.toString().toInt(decimalRadix) } |
| 16 | + val kontrollSiffer1 = hentKontrollSiffer(fodselsnummerListe.take(9), kontrollRekke1) |
| 17 | + val kontrollSiffer2 = hentKontrollSiffer(fodselsnummerListe.take(10), kontrollRekke2) |
| 18 | + return fodselsnummerListe[9] == kontrollSiffer1 && fodselsnummerListe[10] == kontrollSiffer2 |
| 19 | + } |
| 20 | + |
| 21 | + private val kontrollRekke1 = listOf(3, 7, 6, 1, 8, 9, 4, 5, 2) |
| 22 | + private val kontrollRekke2 = listOf(5, 4, 3, 2, 7, 6, 5, 4, 3, 2) |
| 23 | + private const val decimalRadix = 10 |
| 24 | + |
| 25 | + private fun isValidPNumber(dag: Int, maned: Int) = dag > 0 && dag <= 32 && maned > 0 && maned <= 12 |
| 26 | + |
| 27 | + private fun isValidDNumber(dag: Int, maned: Int) = dag > 40 && dag <= 72 && maned > 0 && maned <= 12 |
| 28 | + |
| 29 | + private fun isValidHNumber(dag: Int, maned: Int) = dag > 0 && dag <= 32 && maned > 40 && maned <= 52 |
| 30 | + |
| 31 | + private fun isValidDate(dag: Int, maned: Int) = |
| 32 | + isValidPNumber(dag, maned) || isValidDNumber(dag, maned) || isValidHNumber(dag, maned) |
| 33 | + |
| 34 | + private fun isValidFodselsdato(fodselsnummer: String): Boolean { |
| 35 | + val dag = fodselsnummer.substring(0, 2).toInt(decimalRadix) |
| 36 | + val maned = fodselsnummer.substring(2, 4).toInt(decimalRadix) |
| 37 | + return isValidDate(dag, maned) |
| 38 | + } |
| 39 | + |
| 40 | + private fun hentKontrollSiffer(fodselsnummer: List<Int>, kontrollrekke: List<Int>): Int { |
| 41 | + var sum = 0 |
| 42 | + for (i in fodselsnummer.indices) { |
| 43 | + sum += fodselsnummer[i] * kontrollrekke[i] |
| 44 | + } |
| 45 | + val kontrollSiffer = sum % 11 |
| 46 | + return if (kontrollSiffer != 0) 11 - kontrollSiffer else 0 |
| 47 | + } |
| 48 | + } |
| 49 | +} |
0 commit comments