有没有办法让文字字段输入必须是电子邮件? (在xcode中)

时间:2011-08-19 15:13:05

标签: iphone mysql objective-c xcode ios4

我想创建一个用户登录表单,它需要使用电子邮件而不仅仅是用户名。如果它不是电子邮件,我有什么方法可以弹出警报吗?顺便说一句,所有这些都在xcode中。

4 个答案:

答案 0 :(得分:40)

有一种方法可以使用NSPredicateregular 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];
}

然后,如果电子邮件地址错误,您可以显示警告:

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

答案 1 :(得分:3)

为了使用现代代码更新此帖子,我认为根据akashivskyy's原始目标-c回答发布快速回答会很不错

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

答案 2 :(得分:2)

我在我的应用程序中做了类似的事情,在那里我验证了电子邮件地址字段有2个部分用'@'符号分隔,并且至少2个部分用'''分隔。符号。这不会检查它是否是有效的电子邮件地址,但至少确保它的格式正确。代码示例:

// 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"];
}

如果出现错误,您可以弹出警报,但我选择显示带有错误消息的UILabel,因为它似乎对用户不那么刺耳。在上面的代码中,我检查了电子邮件地址的格式,密码长度,以及密码(输入两次用于验证)匹配。如果未通过所有这些测试,则应用程序不会执行该操作。您可以选择要验证的字段,当然......只是想我会分享我的例子。

答案 3 :(得分:0)

这种方式适合我。

1.check string只有一个@

2.检查至少有一个。在@

之后

2.在@

之后没有任何空格
-(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;
}