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

14,375

Solution 1

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
    }
}

Solution 2

To keep this post updated with modern code, I thought it would be nice to post the swift answer based off of akashivskyy's original objective-c answer

// MARK: Validate
func isValidEmail(email2Test:String) -> Bool {
    let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
    let range = email2Test.rangeOfString(emailRegEx, options:.RegularExpressionSearch)
    let result = range != nil ? true : false
    return result
}    

Solution 3

I did something like this in my app, where I validated that the email address field had 2 parts separated by the '@' symbol, and at least 2 parts separated by a '.' symbol. This does not check that it is a valid email address, but does make sure that it is in the correct format, at least. Code example:

// to validate email address, just checks for @ and . separators
NSArray *validateAtSymbol = [[emailRegisterTextField text] componentsSeparatedByString:@"@"];
NSArray *validateDotSymbol = [[emailRegisterTextField text] componentsSeparatedByString:@"."];

// checks to make sure entries are good (email valid, username available, passwords enough chars, passwords match
if ([passwordRegisterTextField text].length >= 8 &&
    [passwordRegisterTextField text].length > 0 &&
    [[passwordRegisterTextField text] isEqual:[passwordVerifyRegisterTextField text]] &&
    ![currentUser.userExist boolValue] &&
    ![[emailRegisterTextField text] isEqualToString:@""] &&
    ([validateAtSymbol count] == 2) &&
    ([validateDotSymbol count] >= 2)) {

// get user input
NSString *inputEmail = [emailRegisterTextField text];
NSString *inputUsername = [userNameRegisterTextField text];
NSString *inputPassword = [passwordRegisterTextField text];
NSString *inputPasswordVerify = [passwordVerifyRegisterTextField text];

NSLog(@"inputEmail: %@",inputEmail);
NSLog(@"inputUsername: %@",inputUsername);
NSLog(@"inputPassword: %@",inputPassword);
NSLog(@"inputPasswordVerify: %@",inputPasswordVerify);

// attempt create
[currentUser createUser:inputEmail username:inputUsername password:inputPassword passwordVerify:inputPasswordVerify];
}
else {
    NSLog(@"error");
    [errorLabel setText:@"Invalid entry, please recheck"];
}

You can have an alert pop up if something is incorrect, but I chose to display a UILabel with the error message, since it seemed less jarring to the user. In the above code, I checked the format of the email address, the password length, and that the passwords (entered twice for verification) matched. If all of these tests were not passed, the app did not perform the action. You can choose which field you want to validate, of course...just figured I'd share my example.

Share:
14,375
inVINCEable
Author by

inVINCEable

if(user.hasTime == true) { user.updateDesc(); } else { user.workOnSomethingProductive(); }

Updated on June 27, 2022

Comments

  • inVINCEable
    inVINCEable almost 2 years

    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.

  • akashivskyy
    akashivskyy over 12 years
    Yes, replace aTextField with your textField's name. Don't forget that you have to call [self checkEmailAndDisplayAlert] somewhere...
  • akashivskyy
    akashivskyy over 12 years
    @user613231: Glad I could help. ;)
  • iqueqiorio
    iqueqiorio over 9 years
    this works great mostly, If a user types, [email protected], It says this a valid email but its not, is there a way around this?
  • Loic Verrall
    Loic Verrall almost 9 years
    You could also simplify the last 2 lines further to return range != nil ? true : false