Skip to content

Instantly share code, notes, and snippets.

@wilburx9
Last active March 17, 2023 04:58
Show Gist options
  • Save wilburx9/af881334edd9276ad01150e729e5f051 to your computer and use it in GitHub Desktop.
Save wilburx9/af881334edd9276ad01150e729e5f051 to your computer and use it in GitHub Desktop.
Validating card number with Luhn algorithm in dart/flutter
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