Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 840
sudo rm -rf Avatar asked Dec 31 '25 01:12

sudo rm -rf


1 Answers

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;
}
like image 185
WrightsCS Avatar answered Jan 02 '26 14:01

WrightsCS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!