Skip to content

Instantly share code, notes, and snippets.

@naknut
Created January 31, 2018 13:35
Show Gist options
  • Save naknut/da41557fd6fb06634d327a3bab54ad45 to your computer and use it in GitHub Desktop.
Save naknut/da41557fd6fb06634d327a3bab54ad45 to your computer and use it in GitHub Desktop.
Number validation
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