Search code examples
iphonemysqlobjective-cxcodeios4

is there any way to make a Text field entry must be email? (in xcode)


I want to make a user login form and it needs to use emails not just usernames. Is there any way i can make a alert pop up if it is not an email? btw All of this is in xcode.


Solution

  • There is a way using NSPredicate and regular expression:

    - (BOOL)validateEmail:(NSString *)emailStr {
        NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
        NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
        return [emailTest evaluateWithObject:emailStr];
    }
    

    Then, you can display an alert if email address is wrong:

    - (void)checkEmailAndDisplayAlert {
        if(![self validateEmail:[aTextField text]]) {
            // user entered invalid email address
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Enter a valid email address." delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
            [alert show];
            [alert release];
        } else {
            // user entered valid email address
        }
    }