Harish
Harish

Reputation: 2512

Objective C NSString Validation

i have a NSString which has user entered UITextField value, here i need to validate whether the string only contains values like

'a to z' , 'A to z' , '1 to 9'.

i don't want any other characters other than these... Please help me out... i have use NSNumberFormatter for Numbers and NSScanner for Strings, but how to validate both at a time.

Upvotes: 0

Views: 797

Answers (2)

Andrew Tetlaw
Andrew Tetlaw

Reputation: 2689

you can use an NSRegularExpression like so:

    NSString *string1 = @"abc123";
    NSString *string2 = @"!abc123";
    NSError *error = NULL;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[^a-z0-9]" options:NSRegularExpressionCaseInsensitive error:&error];

    NSUInteger numberOfMatches = [regex numberOfMatchesInString:string1 options:0 range:NSMakeRange(0, [string1 length])];
    NSLog(@"string 1 matches: %ld", numberOfMatches);

    numberOfMatches = [regex numberOfMatchesInString:string2 options:0 range:NSMakeRange(0, [string1 length])];
    NSLog(@"string 2 matches: %ld", numberOfMatches);

and change the pattern @"[^a-z0-9]" to suit the characters you want to check for. The ^ means "not in this set", so if any matches are found the field should fail validation.

Upvotes: 1

P.J
P.J

Reputation: 6587

Make UITextField delegate and paste this below code :-

// in -init, -initWithNibName:bundle:, or similar

NSCharacterSet *blockedCharacters = [[[NSCharacterSet alphanumericCharacterSet] invertedSet] retain];

- (BOOL)textField:(UITextField *)field shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)characters
{
    return ([characters rangeOfCharacterFromSet:blockedCharacters].location == NSNotFound);
}

// in -dealloc

[blockedCharacters release];

Hope it helps you

Upvotes: 4

Related Questions