Last active
February 12, 2016 02:37
-
-
Save erd0s/e0153de760090bbe405e to your computer and use it in GitHub Desktop.
Validate credit card number with Luhn algorithm
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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