user2932169
user2932169

Reputation: 1

ios validating text field input for some characters

I am really new to ios development. while validating a text field i must ensure that it contains only 0-9 and special characters like * and #. Please help me out.

- (BOOL)validate:(NSString *)string{
    NSString *exp = @"^([0-9]+)?(\\.([0-9]{1,2})?)?$";
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:exp options:NSRegularExpressionCaseInsensitive error:nil];
    NSUInteger numberOfMatches = [regex numberOfMatchesInString:string options:0 range:NSMakeRange(0, [string length])];
    if (numberOfMatches == 0)
        return NO;
    return YES;
}

Upvotes: 0

Views: 2372

Answers (2)

slecorne
slecorne

Reputation: 1718

You may try this:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string  {

NSCharacterSet *numberAndSpecialCharsSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789*#"];

return ([string rangeOfCharacterFromSet:numberAndSpecialCharsSet].location==NSNotFound);

}

Upvotes: 0

Bhumeshwer katre
Bhumeshwer katre

Reputation: 4671

Try this:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string  {

    NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789*#"] invertedSet];

    NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];

    return [string isEqualToString:filtered];
}

Upvotes: 1

Related Questions