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

    #1
    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.
     
  2. macrumors regular

    #2
    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

    Eraserhead

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

    #4
    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; 
    } 
    
     

Share This Page