Posted By

Scooter on 03/07/09


Tagged


Versions (?)

Luhn Algorithm


 / Published in: ASP
 

URL: http://reusablecode.blogspot.com/2009/03/luhn-algorithm.html

For verifying credit card numbers.

  1. <%
  2. ' Copyright (c) 2008, reusablecode.blogspot.com; some rights reserved.
  3. '
  4. ' This work is licensed under the Creative Commons Attribution License. To view
  5. ' a copy of this license, visit http://creativecommons.org/licenses/by/3.0/ or
  6. ' send a letter to Creative Commons, 559 Nathan Abbott Way, Stanford, California
  7. ' 94305, USA.
  8.  
  9. ' Luhn (mod 10) algorithm
  10. function luhn(byVal input)
  11. dim sum
  12. dim odd
  13. dim currentDigit
  14. dim regEx
  15.  
  16. input = CStr(input)
  17. sum = 0
  18. odd = CBool(len(input) mod 2)
  19.  
  20. ' Remove any non-numeric characters.
  21. if not isNumeric(input) then
  22. set regEx = new RegExp
  23. regEx.Global = true
  24. regEx.Pattern = "\D"
  25. input = regEx.Replace(input, "")
  26. set regEx = nothing
  27. end if
  28.  
  29. ' Calculate sum of digits.
  30. for i = 1 to len(input)
  31. currentDigit = cint(mid(input, i, 1))
  32.  
  33. if odd then
  34. sum = sum + currentDigit
  35. else
  36. if currentDigit * 2 > 9 then
  37. sum = sum + (currentDigit * 2 - 9)
  38. else
  39. sum = sum + (currentDigit * 2)
  40. end if
  41. end if
  42.  
  43. odd = not odd
  44. next
  45.  
  46. ' Check validity.
  47. if sum mod 10 = 0 then
  48. luhn = true
  49. else
  50. luhn = false
  51. end if
  52. end function
  53.  
  54. ' Unit test - expected result is true
  55. if luhn("446667651") then
  56. response.write "true"
  57. else
  58. response.write "false"
  59. end if
  60. %>

Report this snippet  

You need to login to post a comment.