Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

Flybro

macrumors newbie
Original poster
May 21, 2009
11
0
Down Under
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.

Cheers,
F.
 
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:
 
I would do it with NSFormatter like you do if you want just a number as it will work better.
 
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?

Code:
-(bool)isPartialStringValid:(NSString *)partialString 
           newEditingString:(NSString**)newString 
           errorDescription:(NSString**)error 
{ 
	
  NSRange inRange;
  NSCharacterSet *allowedChars = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-()<>@ ._"] invertedSet];
  inRange = [partialString rangeOfCharacterFromSet:allowedChars];
		
  if(inRange.location != NSNotFound)
   {
     NSLog(@"Name input contains disallowed character.");
     NSBeep();
     return NO;
   }

   *newString = partialString;
   return YES; 
}
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.