gvalid_rule_luhn.go 672 B

12345678910111213141516171819202122232425262728
  1. // Copyright 2018 gf Author(https://github.com/gogf/gf). All Rights Reserved.
  2. //
  3. // This Source Code Form is subject to the terms of the MIT License.
  4. // If a copy of the MIT was not distributed with this file,
  5. // You can obtain one at https://github.com/gogf/gf.
  6. package gvalid
  7. // checkLuHn checks <value> with LUHN algorithm.
  8. // It's usually used for bank card number validation.
  9. func checkLuHn(value string) bool {
  10. var (
  11. sum = 0
  12. nDigits = len(value)
  13. parity = nDigits % 2
  14. )
  15. for i := 0; i < nDigits; i++ {
  16. var digit = int(value[i] - 48)
  17. if i%2 == parity {
  18. digit *= 2
  19. if digit > 9 {
  20. digit -= 9
  21. }
  22. }
  23. sum += digit
  24. }
  25. return sum%10 == 0
  26. }