开发者

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 e开发者_Go百科mail? btw All of this is in xcode.


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


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
}    


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.


This way works well for me.

1.check string has only one @

2.check at least has one . after @

2.with out any space after @

-(BOOL)checkEmailString :(NSString*)email{
//DLog(@"checkEmailString = %@",email);
BOOL emailFlg = NO;
NSArray *atArr = [email componentsSeparatedByString:@"@"];

//check with one @
if ([atArr count] == 2) {
    NSArray *dotArr = [atArr[1] componentsSeparatedByString:@"."];

    //check with at least one .
    if ([dotArr count] >= 2) {
        emailFlg = YES;

        //all section can't be
        for (int i = 0; i<[dotArr count]; i++) {

            if ([dotArr[i] length] == 0 ||
                [dotArr[i] rangeOfString:@" "].location != NSNotFound) {
                emailFlg = NO;
            }
        }
    }
}

return emailFlg;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜