Created
January 31, 2018 13:35
-
-
Save naknut/da41557fd6fb06634d327a3bab54ad45 to your computer and use it in GitHub Desktop.
Number validation
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
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { | |
let newText = ((textField.text as NSString?) ?? "").replacingCharacters(in: range, with: string) | |
guard newText.count > 0 else { | |
return true | |
} | |
guard (newText.filter{ $0 == Character(Locale.current.decimalSeparator!) } as [Character]).count <= 1 else { // Make sure we only have one decimal separator | |
return false | |
} | |
let numbersSet: Set<Character> = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] | |
var withoutSeperator = newText | |
if let separatiorIndex = withoutSeperator.index(of: Character(Locale.current.decimalSeparator!)) { | |
withoutSeperator.remove(at: separatiorIndex) | |
} | |
return Set(withoutSeperator).isSubset(of: numbersSet) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment