How do I force the user to enter only numbers in a text field?
Replies
click on the text field and change the keyboard type from the right panel
You can also use controlTextDidChange
override func controlTextDidChange(obj: NSNotification) {
let object = obj.object as! NSTextField
if object !== cellTextField { return } /
someCellTextFieldHasChanged = true /
let lastChar = object.stringValue.count - 1 /
guard let typed = object.stringValue.lastChar else { return } /
if !"0123456789".containsChar(typed) {
cellTextField!.stringValue = cellTextField!.stringValue[0..<lastChar]
}
}
ShinehahGnolaum wrote:
How do I force the user to enter only numbers in a text field?
What platform are you working on? So far you’ve got one iOS answer and one macOS answer!
Can you be more precise about what you mean by “numbers”. Are you looking to filter out everything that’s not a digit? Or do you want to handle things like decimal points? And do you want to force the user to use Western Arabic digits? Or will you accept other digits (for example, Eastern Arabic digits)?
toshb wrote:
click on the text field and change the keyboard type from the right panel
This is a good idea but be aware that it doesn’t prevent the user from entering text via other means (most notably, via Paste). You can catch other modifications via the
-shouldChangeTextInRange:replacementText:
callback.
Also, if you want to force Western Arabic digits you’ll want to use ASCII Capable Number Pad (
UIKeyboardTypeASCIICapableNumberPad
) rather than
Number Pad (
UIKeyboardTypeNumberPad
).
Claude31 wrote:
if !"0123456789".containsChar(typed) { cellTextField!.stringValue = cellTextField!.stringValue[0..<lastChar] }
Two things:
This assumes the user is using Western Arabic digits.
On macOS, you may be better off attaching a number formatter to your text field. You can set that up in IB or via the
of the text field cell.formatter
Share and Enjoy
—
Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware
let myEmail = "eskimo" + "1" + "@apple.com"
This proposed solution doesn't address paste nor an external keyboard.
In the case of UITextField, you would want to implement the textField(_:shouldChangeCharactersIn:replacementString:) delegate, then filter out the characters you don't want in the input.
If you only want decimal characters, you could use NSCharacterSet's decimalDigits and filter out characters not present in that set.