Last active
July 3, 2024 11:34
-
-
Save wilburx9/af881334edd9276ad01150e729e5f051 to your computer and use it in GitHub Desktop.
Validating card number with Luhn algorithm in dart/flutter
This file contains hidden or 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
static String validateCardNumWithLuhnAlgorithm(String input) { | |
if (input.isEmpty) { | |
return Strings.fieldReq; | |
} | |
input = getCleanedNumber(input); | |
if (input.length < 8) { // No need to even proceed with the validation if it's less than 8 characters | |
return Strings.numberIsInvalid; | |
} | |
int sum = 0; | |
int length = input.length; | |
for (var i = 0; i < length; i++) { | |
// get digits in reverse order | |
int digit = int.parse(input[length - i - 1]); | |
// every 2nd number multiply with 2 | |
if (i % 2 == 1) { | |
digit *= 2; | |
} | |
sum += digit > 9 ? (digit - 9) : digit; | |
} | |
if (sum % 10 == 0) { | |
return null; | |
} | |
return Strings.numberIsInvalid; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment