1. Welcome to the new MacRumors forums. See our announcement and read our FAQ

How to catch characters in NSTextField?

Discussion in 'Mac Programming' started by Flybro, May 31, 2009.

  1. macrumors newbie

    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.

  2. macrumors regular

    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:
  3. macrumors G4


    I would do it with NSFormatter like you do if you want just a number as it will work better.
  4. macrumors newbie

    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?

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

Share This Page