Interface builder has this Custom Formatter that can be dragged to text fields.
But this thing has no properties at all and the documentation, as typical with Apple, is non-existent.
I need to create a formatter than can accept numbers, texts from the alphanumeric set and underscore and reject everything else.
I suspect this Custom Formatter is what I need but how do I use that? Or is that possible to do what I need using regular formatters existent on interface builder?
Can you give an example using interface builder?
Thanks.
The NSFormatter class is an abstract class, so you need to subclass it. On that you need to implement the following methods.
- (BOOL)isPartialStringValid:(NSString *)partialString newEditingString:(NSString **)newString errorDescription:(NSString **)error;
- (NSString *)stringForObjectValue:(id)obj;
- (BOOL)getObjectValue:(out id *)obj forString:(NSString *)string errorDescription:(out NSString **)error;
Create a subclass like:
.h
@interface MyFormatter : NSFormatter
@end
.m
@implementation MyFormatter
- (BOOL)isPartialStringValid:(NSString *)partialString newEditingString:(NSString **)newString errorDescription:(NSString **)error
{
// In this method you need to write the validation
// Here I'm checking whether the first character entered in the textfield is 'a' if yes, It's invalid in my case.
if ([partialString isEqualToString:@"a"])
{
NSLog(@"not valid");
return false;
}
return YES;
}
- (NSString *)stringForObjectValue:(id)obj
{
// Here you return the initial value for the object
return @"Midhun";
}
- (BOOL)getObjectValue:(out id *)obj forString:(NSString *)string errorDescription:(out NSString **)error
{
// In this method we can parse the string and pass it's value (Currently all built in formatters won't support so they just return NO, so we are doing the same here. If you are interested to do any parsing on the string you can do that here and pass YES after a successful parsing
// You can read More on that here: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSFormatter_Class/index.html#//apple_ref/occ/instm/NSFormatter/getObjectValue:forString:errorDescription:
return NO;
}
@end