有没有办法让文本字段条目必须是电子邮件?(在 xcode 中)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7123667/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
is there any way to make a Text field entry must be email? (in xcode)
提问by inVINCEable
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.
我想制作一个用户登录表单,它需要使用电子邮件而不仅仅是用户名。如果不是电子邮件,有什么办法可以弹出警报吗?顺便说一句,所有这些都在 xcode 中。
回答by akashivskyy
There is a way using NSPredicateand regular expression:
有一种使用NSPredicate和正则表达式的方法:
- (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
}
}
回答by inVINCEable
To keep this post updated with modern code, I thought it would be nice to post the swift answer based off of akashivskyy'soriginal objective-c answer
为了使用现代代码更新这篇文章,我认为根据akashivskyy 的原始 Objective-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
}
回答by superjessi
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:
我在我的应用程序中做了类似的事情,在那里我验证了电子邮件地址字段有 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"];
}
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.
如果出现错误,您可以弹出警告,但我选择显示UILabel
带有错误消息的 ,因为它对用户来说似乎不那么刺耳。在上面的代码中,我检查了电子邮件地址的格式、密码长度以及密码(输入两次以进行验证)是否匹配。如果所有这些测试都没有通过,则应用程序不会执行该操作。当然,您可以选择要验证的字段……只是想我会分享我的示例。
回答by god0911
This way works well for me.
这种方式对我很有效。
1.check string has only one @
1.check字符串只有一个@
2.check at least has one . after @
2.check至少有一个。后 @
2.with out any space after @
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;
}