Skip to content

Instantly share code, notes, and snippets.

@erd0s
Last active February 12, 2016 02:37
Show Gist options
  • Save erd0s/e0153de760090bbe405e to your computer and use it in GitHub Desktop.
Save erd0s/e0153de760090bbe405e to your computer and use it in GitHub Desktop.
Validate credit card number with Luhn algorithm
/**
* String extension to validate credit card number.
* Automatically strips any whitespace from the string but otherwise the string
* should not contain and non-numeric characters.
*/
extension String {
func validateLuhn() -> Bool {
let nsStringVersionNoSpaces = (self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) as NSString)
if (self.rangeOfString("^[0-9]+$", options: .RegularExpressionSearch) == nil) {
return false
}
let lastOdd = self.characters.count - 2
let lastEven = self.characters.count - 3
var result = 0
var i: Int
for i = lastOdd; i >= 0; i-=2 {
var oddNumber = Int(nsStringVersionNoSpaces.substringWithRange(NSRange(location: i, length: 1)))! * 2
if oddNumber >= 10 {
oddNumber -= 9
}
result += oddNumber
}
for i = lastEven; i >= 0; i-=2 {
result += Int(nsStringVersionNoSpaces.substringWithRange(NSRange(location: i, length: 1)))!
}
result += Int(nsStringVersionNoSpaces.substringWithRange(NSRange(location: self.characters.count-1, length: 1)))!
if result % 10 == 0 {
return true
}
else {
return false
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment