Codesnipp.it Social Code Sharing

Scott Rapson

limit input length and char type of UITextfield

by Scott Rapson on Feb 18, 2011

/* use this code with a UITextField to set the length limit and character restrictions. Use in your method for a predefined textfield with appropriate outlets etc. My example uses userName as the name of the textfield */ //text field returns userName and sets nameLabel. Checks string if its long or has invalid characters - (BOOL)textFieldShouldReturn:(UITextField *)theTextField { [userName resignFirstResponder]; // allow a-z, A-Z, 0-9 characters only BOOL legal = YES; for (int i = 0; i < [userName.text length]; ++i) { int myChar = [userName.text characterAtIndex:i]; if ((myChar < 48) || (myChar > 122) || ((myChar > 57) && (myChar < 65)) || ((myChar > 90) && (myChar < 97))) { legal = NO; } } if ((!legal) || ([userName.text length] == 0)) { //the stuff entered is legal //update label or whatever and dismiss keyboard [userName becomeFirstResponder]; return YES; } //length check if ([userName.text length] > 15) userName.text = [userName.text substringWithRange:NSMakeRange(0, 15)]; return NO; }

Can't see the comments? Please login first :)