7

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 there any library that can't make this easy for me so I don't have to write regular expressions.

spentak
  • 4,627
  • 15
  • 62
  • 90

3 Answers3

17

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.

chown
  • 51,908
  • 16
  • 134
  • 170
  • Looks good, I haven't looked into the text field delegate before. – sunkencity Oct 05 '11 at 17:50
  • chown, this works great but doesn't seem to handle delete key events. Returns NO if phone is >= 10 therefore doesn't change upon delete – spentak Oct 05 '11 at 18:41
  • Oh, you are correct. Replace `if (textField.text.length >= 10)` with `if (textField.text.length + string.length > 10)` – chown Oct 05 '11 at 18:53
  • Using tags (magic numbers) to distinguish your views is not a very clever code. Why not just compare "textField == self.emailInput" assuming you have two properties self.emailInput and self.phoneInput? Code will be easier to read and less prone to errors. Also, in general, regular expressions would give you better results: "[0-9]{10}" for phone numbers and something like "[a-zA-Z][a-zA-Z.0-9]{2,30}@([a-zA-Z][a-zA-Z0-9]{1,30}[.])+[a-zA-Z]{2,3} for emails. Note that I didn't check the email regexp, it's just something that could possibly work and I don't remember how exactly it should look like. – Sulthan Nov 02 '11 at 12:54
3

Here's a simple way of ensuring phonenumber length in the UIViewController that has the text field in it's view.

- (void)valueChanged:(id)sender
{
    if ([[[self phoneNumberField] text] length] > 10) {
        [[self phoneNumberField] setText:[[[self phoneNumberField] text] 
          substringToIndex:10]]; 
    } 
}

- (void) viewWillAppear:(BOOL)animated
{
    [[self phoneNumberField] addTarget:self 
                            action:@selector(valueChanged:) 
                            forControlEvents:UIControlEventEditingChanged];
}

For emails I suppose you want to check against a regexp when it loses focus.

sunkencity
  • 3,482
  • 1
  • 22
  • 19
0

Here's Simple Example for UITextField Validation while type in keyboard other characters not displaying

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
//UITextField *tf_phonenumber,*tf_userid;
if (textField.text<=10) {
char c=*[string UTF8String];
if (tf_phonenumber==textField)      //PhoneNumber /Mobile Number
{
    if ((c>='0' && c<='9')||(c==nil)) {
        return YES;
    }
    else
        return NO;
}
if (tf_userid==textField)           //UserID validation
{
    if ((c>='a' && c<='z')||(c>='A' && c<='Z')||(c==' ')||(c==nil)) {
        return YES;
    }
    else
        return NO;
}
    return YES;
}
else{
    return NO;
}
}
GNANA VEL
  • 21
  • 4