class CardValidator : ValidatorNew<String> {
override fun validate(value: String): Pair<Boolean, ValidationError?> {
if (value.length != 12 && value.length != 16)
return false to ValidationError.MUST_EQUAL_LENGTH
if (value.any { !it.isDigit() })
return false to ValidationError.INVALID_CHARACTERS
val digits = value.map { it.digitToInt() }
val checksum = digits.reversed().mapIndexed { index, digit ->
if (index % 2 == 1) {
val doubled = digit * 2
if (doubled > 9) doubled - 9 else doubled
} else {
digit
}
}.sum()
if (checksum % 10 != 0)
return false to ValidationError.INVALID_FORMAT
return true to null
}
}