What are best practices for validating email addresses on iOS 2.0
What is the cleanest way to validate an email address that a user enters on iOS 2.0?
NOTE : This is a historical question that is specific to iOS 2.0 and due to its age and how many other questions are linked to it it cannot be retired and MUST NOT be changed to a "modern" question.
The answer to Using a regular expression to validate an email address explains in great detail that the grammar specified in RFC 5322 is too complicated for primitive regular expressions.
I recommend a real parser approach like MKEmailAddress.
As quick regular expressions solution see this modification of DHValidation:
- (BOOL) validateEmail: (NSString *) candidate {
NSString *emailRegex =
@"(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:.[a-z0-9!#$%&'*+/=?^_`{|}"
@"~-]+)*|"(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-"
@"x7f]|\[x01-x09x0bx0cx0e-x7f])*")@(?:(?:[a-z0-9](?:[a-"
@"z0-9-]*[a-z0-9])?.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|[(?:(?:25[0-5"
@"]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-"
@"9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21"
@"-x5ax53-x7f]|\[x01-x09x0bx0cx0e-x7f])+)])";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES[c] %@", emailRegex];
return [emailTest evaluateWithObject:candidate];
}
Read the RFC. Almost everyone that thinks they know how to parse/clean/validate an email address is wrong.
http://tools.ietf.org/html/rfc2822 Section 3.4.1 is very useful. Notice
dtext = NO-WS-CTL / ; Non white space controls %d33-90 / ; The rest of the US-ASCII %d94-126 ; characters not including "[", ; "]", or ""
Yes, that means +, ', etc are all legit.
The best solution I have found so far (and the one I ended up going with) is to add RegexKitLite To the project which gives access to regular expressions via NSString Categories.
It is quite painless to add to the project and once in place, any of the regular expression email validation logic will work.
链接地址: http://www.djcxy.com/p/42190.html上一篇: 域名电子邮件验证