Skip to main content

is_valid_credit_card

Function is_valid_credit_card 

Source
pub fn is_valid_credit_card(value: &str) -> bool
Expand description

Validate a credit card number using the Luhn algorithm.

The Luhn algorithm (also known as the “modulus 10” algorithm) is a simple checksum formula used to validate identification numbers such as credit card numbers, IMEI numbers, and others.

§Algorithm

  1. Starting from the rightmost digit (check digit) and moving left, double the value of every second digit.
  2. If the result of doubling is greater than 9, subtract 9.
  3. Sum all the digits.
  4. The total modulo 10 must equal 0.

§Arguments

  • value - The credit card number as a string (may contain spaces or hyphens)

§Returns

true if the number is valid according to the Luhn algorithm, false otherwise.

§Example

use sqlmodel_core::validate::is_valid_credit_card;

assert!(is_valid_credit_card("4539578763621486"));  // Valid Visa
assert!(is_valid_credit_card("4539-5787-6362-1486")); // With dashes
assert!(is_valid_credit_card("4539 5787 6362 1486")); // With spaces
assert!(!is_valid_credit_card("1234567890123456")); // Invalid