View Full Version : How to catch characters in NSTextField?
May 31, 2009, 04:59 AM
Does anyone know how to limit type of characters that can be entered into an NSTextField?. I have a special situation where only some of the characters from the alphabet should be entered. For example, only a-zA-Z0-9+_- should be allowed. Also, how to trim spaces at the beginning and the end of the string entered into NSTextField.
It's easy by regex but what I really like is catch them at the moment when they are entered and refuse.
May 31, 2009, 07:54 AM
As far as I know, there are two ways:
– Subclass NSTextField and override interpretKeyEvents: or keyDown:
– Create and use a subclass of NSFormatter and implement the required logic in isPartialStringValid:newEditingString:errorDescription:
May 31, 2009, 09:55 AM
I would do it with NSFormatter like you do if you want just a number as it will work better.
Jun 3, 2009, 09:59 AM
Implemented and working but..
I don't have any smallest idea how to disallow [:space:] at the beginning and the end but leave them untouched in the middle of the string.
Perhaps I should do this by post-processing this string with a little help from stringByTrimmingCharactersInSet?
NSCharacterSet *allowedChars = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-()<>@ ._"] invertedSet];
inRange = [partialString rangeOfCharacterFromSet:allowedChars];
if(inRange.location != NSNotFound)
NSLog(@"Name input contains disallowed character.");
*newString = partialString;