Last active
January 14, 2017 23:16
-
-
Save richy486/c32d272639631032257dcc4cc7ca6583 to your computer and use it in GitHub Desktop.
Swift number validator
This file contains 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
let valid = ["3.14159265", "123.12", "2", "56754", "92929292929292.12", "0.21", "3.1","3","-3","0","0.0","1.0","0.1", ".12", "-12", "-34.6"] | |
let invalid = ["e666.76","a"," ","-"," -1","--1", "2..3", "2-", "2...3", "2.4.3", "5-6-7"] | |
func isValidNumber(numberString: String) -> Bool { | |
let numberFormatter = NumberFormatter() | |
// print(numberFormatter.decimalSeparator) | |
let decimalSeparator = numberFormatter.decimalSeparator ?? "." | |
let regularExpression = "[+-]?((\\d+(\\\(decimalSeparator)\\d*)?)|(\\\(decimalSeparator)\\d+))" | |
// print(regularExpression) | |
guard let regex = try? NSRegularExpression(pattern: regularExpression, options: .caseInsensitive) else { | |
fatalError("fail regex \(numberString)") | |
} | |
guard let firstMatch = regex.firstMatch(in: numberString, options: .init(rawValue: 0), range: NSMakeRange(0, numberString.characters.count)) else { | |
return false | |
} | |
// print("first match: \(firstMatch.range)") | |
let startIndex = numberString.index(numberString.startIndex, offsetBy: firstMatch.range.location) | |
let endIndex = numberString.index(numberString.startIndex, offsetBy: firstMatch.range.location + firstMatch.range.length - 1) | |
let matchString = numberString[startIndex...endIndex] | |
// print("match string: \(matchString)") | |
return numberString == matchString | |
} | |
for testString in valid { | |
let isValid = isValidNumber(numberString: testString) | |
if !isValid { | |
print("error, should be valid: \(testString)") | |
} | |
print("is valid: \(isValid)") | |
} | |
for testString in invalid { | |
let isValid = isValidNumber(numberString: testString) | |
if isValid { | |
print("error, should be invalid: \(testString)") | |
} | |
print("is invalid: \(!isValid)") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment