0

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;
}
5
  • have you tried anything, any code? Commented Dec 12, 2013 at 9:28
  • You can set the keyboard type so it will contain only numbers and special characters. look here : developer.apple.com/library/ios/documentation/StringsTextFonts/… Commented Dec 12, 2013 at 9:31
  • but in ipad, the user has an option to change keyboard. it has an option of ABC in numeric keyboard. Commented Dec 12, 2013 at 9:34
  • This might helps you, stackoverflow.com/questions/2297102/… Commented Dec 12, 2013 at 9:35
  • 1
    @user2932169 Add code in body instead of comment. It should be more readable. Commented Dec 12, 2013 at 9:35

2 Answers 2

1

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];
}
Sign up to request clarification or add additional context in comments.

Comments

0

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);

}

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.