本文介绍了检查电子邮件地址在 iOS 上是否有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能的重复:
验证电子邮件地址的最佳做法在 iOS 2.0 上的 Objective-C 中?
我正在开发一个 iPhone 应用程序,我需要用户在登录时提供他的电子邮件地址.
I am developing an iPhone application where I need the user to give his email address at login.
检查电子邮件地址是否为有效电子邮件地址的最佳方法是什么?
What is the best way to check if an email address is a valid email address?
推荐答案
好可可功能:
-(BOOL) NSStringIsValidEmail:(NSString *)checkString
{
BOOL stricterFilter = NO; // Discussion http://blog.logichigh.com/2010/09/02/validating-an-e-mail-address/
NSString *stricterFilterString = @"^[A-Z0-9a-z\._%+-]+@([A-Za-z0-9-]+\.)+[A-Za-z]{2,4}$";
NSString *laxString = @"^.+@([A-Za-z0-9-]+\.)+[A-Za-z]{2}[A-Za-z]*$";
NSString *emailRegex = stricterFilter ? stricterFilterString : laxString;
NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
return [emailTest evaluateWithObject:checkString];
}
关于松散与严格的讨论 - http://blog.logichigh.com/2010/09/02/validating-an-e-mail-address/
Discussion on Lax vs. Strict - http://blog.logichigh.com/2010/09/02/validating-an-e-mail-address/
而且因为类别更好,您还可以添加一个界面:
And because categories are just better, you could also add an interface:
@interface NSString (emailValidation)
- (BOOL)isValidEmail;
@end
实施
@implementation NSString (emailValidation)
-(BOOL)isValidEmail
{
BOOL stricterFilter = NO; // Discussion http://blog.logichigh.com/2010/09/02/validating-an-e-mail-address/
NSString *stricterFilterString = @"^[A-Z0-9a-z\._%+-]+@([A-Za-z0-9-]+\.)+[A-Za-z]{2,4}$";
NSString *laxString = @"^.+@([A-Za-z0-9-]+\.)+[A-Za-z]{2}[A-Za-z]*$";
NSString *emailRegex = stricterFilter ? stricterFilterString : laxString;
NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
return [emailTest evaluateWithObject:self];
}
@end
然后利用:
if([@"[email protected]" isValidEmail]) { /* True */ }
if([@"InvalidEmail@notreallyemailbecausenosuffix" isValidEmail]) { /* False */ }
这篇关于检查电子邮件地址在 iOS 上是否有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!