Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Email validation on textField in iOS

In iOS App, how to add Email validation on UITextField?

like image 810
ios Avatar asked Mar 25 '11 03:03

ios


People also ask

How do I validate an email in Swift?

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.

How do I validate an email address in Objective C?

Validate email address by calling any of the above method. For example, [Utility isValidEmailAddress:@"[email protected]"]; OR [Utility validateEmail:@"[email protected]"];

What is email validation in Javascript?

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.


1 Answers

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]; } 
like image 183
Rog Avatar answered Oct 15 '22 10:10

Rog