0

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.

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

3 Comments

how can i allow ' _ ' , ' @ ' ...?
@HarishSaran Check question you have asked
You can use characterSetWithCharactersInString: if you just want to type out the characters you're allowing. If you like the results of Prateek's solution, but just want to add _ and @ you could use NSMutableCharacterSet (just union together them together, making the second set with characterSetWithCharactersInString:. Hard to be sure from the docs, but I'm pretty sure that the alphanumericCharacterSet will include things you wouldn't typically think of as a-z, like ç
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.