sudo rm -rf
sudo rm -rf

Reputation: 29524

How to verify UITextField text?

I need to make sure that the user is only entering numbers into my textfield. I have the keyboard set to numbers, but if the user is using an external keyboard they might enter a letter. How can I detect if any characters in my textfield.text are characters instead of numbers?

Thanks!

Upvotes: 3

Views: 909

Answers (3)

WrightsCS
WrightsCS

Reputation: 50707

You can choose what characters can input into the textField

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

    /*  this ensures that ONLY numbers can be entered, no matter what kind of keyboard is used  */
    NSCharacterSet *myCharSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];

    for (int i = 0; i < [string length]; i++) {
        unichar c = [string characterAtIndex:i];
        if (![myCharSet characterIsMember:c]) {
            return NO;
        }
    }

    /*  this allows you to choose how many characters can be used in the textField  */
    NSUInteger newLength = [textField.text length] + [string length] - range.length;
    return (newLength > 7) ? NO : YES;
}

Upvotes: 4

Ole Begemann
Ole Begemann

Reputation: 135548

Implement textField:shouldChangeCharactersInRange:replacementString: in the text field's delegate and return NO if the passed string contains invalid characters.

Upvotes: 1

ipraba
ipraba

Reputation: 16543

Whenever the user enters a key this textfield delegate will be called.

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

Inside this check whether the text contains characters. if it is do your action. like promptimg a alert or something.

Upvotes: 1

Related Questions