I need a way to ensure that phone numbers have 10 digits with no other characters ie () - and make sure that email addresses are valid emails (formatted correctly).
Is t
This will check a UITextField for a proper email and phone number of 10 digits or less.
Add this method to the textFields delegate then check if the characters it is about to change should be added or not.
Return YES
or NO
depending on the text field, how many characters are currently in it, and what characters it wants to add:
#define ALPHA @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
#define NUMERIC @"1234567890"
#define ALPHA_NUMERIC ALPHA NUMERIC
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSCharacterSet *unacceptedInput = nil;
switch (textField.tag) {
// Assuming EMAIL_TextField.tag == 1001
case 1001:
if ([[textField.text componentsSeparatedByString:@"@"] count] > 1)
unacceptedInput = [[NSCharacterSet characterSetWithCharactersInString:[ALPHA_NUMERIC stringByAppendingString:@".-"]] invertedSet];
else
unacceptedInput = [[NSCharacterSet characterSetWithCharactersInString:[ALPHA_NUMERIC stringByAppendingString:@".!#$%&'*+-/=?^_`{|}~@"]] invertedSet];
break;
// Assuming PHONE_textField.tag == 1002
case 1002:
if (textField.text.length + string.length > 10) {
return NO;
}
unacceptedInput = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
break;
default:
unacceptedInput = [[NSCharacterSet illegalCharacterSet] invertedSet];
break;
}
return ([[string componentsSeparatedByCharactersInSet:unacceptedInput] count] <= 1);
}
Also, check out these 2 articles:
Auto-formatting phone number UITextField on the iPhone
PhoneNumberFormatter.