Skip to content

Instantly share code, notes, and snippets.

@iggym
Last active December 20, 2015 11:29
Show Gist options
  • Save iggym/6124287 to your computer and use it in GitHub Desktop.
Save iggym/6124287 to your computer and use it in GitHub Desktop.
UITextField Validation
// You can add/tailor the acceptable values here...
#define CHARACTERS @" ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
#define CHARACTERS_NUMBERS [CHARACTERS stringByAppendingString:@"1234567890"]
/*---------------------------------------------------
* Called whenever user enters/deletes character
*--------------------------------------------------*/
- (BOOL)textField:(UITextField *)textField
shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string
{
// These are the characters that are ~not~ acceptable
NSCharacterSet *unacceptedInput =
[[NSCharacterSet characterSetWithCharactersInString:CHARACTERS] invertedSet];
// Create array of strings from incoming string using the unacceptable
// characters as the trigger of where to split the string.
// If array has more than one entry, there was at least one unacceptable character
if ([[string componentsSeparatedByCharactersInSet:unacceptedInput] count] > 1)
return NO;
else
return YES;
}
//see http://iosdevelopertips.com/user-interface/validate-user-input-in-uitextfield-with-smarts-to-properly-manage-copy-and-paste.html
#define ALPHA @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
#define NUMERIC @"1234567890"
#define ALPHA_NUMERIC ALPHA NUMERIC
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSCharacterSet *unacceptedInput = nil;
if ([[textField.text componentsSeparatedByString:@"@"] count] > 1) {
unacceptedInput = [[NSCharacterSet characterSetWithCharactersInString:[ALPHA_NUMERIC stringByAppendingString:@".-"]] invertedSet];
} else {
unacceptedInput = [[NSCharacterSet characterSetWithCharactersInString:[ALPHA_NUMERIC stringByAppendingString:@".!#$%&'*+-/=?^_`{|}~@"]] invertedSet];
}
return ([[string componentsSeparatedByCharactersInSet:unacceptedInput] count] <= 1);
}
//see http://stackoverflow.com/questions/7707906/how-to-check-if-uitextfields-text-is-valid-email
//Other possible solutions
//http://stackoverflow.com/questions/5428304/email-validation-on-textfield-in-iphone-sdk
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment