In iOS App, how to add Email validation on UITextField?
Three Methods to Validate Email in SwiftUsing functions of Swift NSPredicate class to match an email address input with a regular expression. Creating a custom class conforming to RawRepresentable which initializes only if a valid email address is provided.
Validate email address by calling any of the above method. For example, [Utility isValidEmailAddress:@"[email protected]"]; OR [Utility validateEmail:@"[email protected]"];
Email validation is one of the vital parts of authenticating an HTML form. Email is a subset or a string of ASCII characters, divided into two parts using @ symbol.
Use 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]; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With