In iOS App, how to add Email validation on UITextField?
See Question&Answers more detail:osUse NSPredicate and Regex:
- (BOOL)validateEmailWithString:(NSString*)email
{
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:email];
}
For a bunch of emails separated by a comma:
- (NSMutableArray*)validateEmailWithString:(NSString*)emails
{
NSMutableArray *validEmails = [[NSMutableArray alloc] init];
NSArray *emailArray = [emails componentsSeparatedByString:@","];
for (NSString *email in emailArray)
{
NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
if ([emailTest evaluateWithObject:email])
[validEmails addObject:email];
}
return [validEmails autorelease];
}
Edited Answer: (It also validates extra dots )
- (BOOL)validateEmailWithString:(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];
}