45

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

Cœur
  • 37,241
  • 25
  • 195
  • 267
ios
  • 6,134
  • 20
  • 71
  • 103

13 Answers13

147

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];
}
rosshump
  • 370
  • 1
  • 4
  • 21
Rog
  • 18,602
  • 6
  • 76
  • 97
  • @Prerak see my edited answer above. This will return an array with all the valid emails. – Rog Mar 25 '11 at 05:17
  • 3
    I tried to test this regex with the email address `email@provider..com` (with two dots after `provider`) and it passed. Is it an invalid email address? – Eduardo Coelho Jun 27 '12 at 01:47
  • how to restrict the user to enter his email id as only @gmail.com in text field. – venki May 14 '14 at 07:07
  • @EduardoCoelho if thats the case run a "string replace" before attempting to validate. emailString = [emailString stringByReplacingOccurrencesOfString:@".." withString:@"."]; – Louie Aug 08 '14 at 22:13
  • 1
    also ' is a valid character in an email address. The regex should be `"[A-Z0-9a-z'._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}"` – Luca Torella Sep 05 '16 at 15:17
  • 1
    ' ' [blank space] in emailId is not getting recognised as incorrect email, is it ok? – rathodbhavikk Sep 28 '17 at 08:07
  • What will happen if you have a Chinese character in your email? – Corbin Miller May 06 '19 at 23:20
18

Try this out
This checks exactly with top level domain names along with validation.


- (BOOL)validateEmail:(NSString *)inputText {
    NSString *emailRegex = @"[A-Z0-9a-z][A-Z0-9a-z._%+-]*@[A-Za-z0-9][A-Za-z0-9.-]*\\.[A-Za-z]{2,6}"; 
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex]; 
    NSRange aRange;
    if([emailTest evaluateWithObject:inputText]) {
        aRange = [inputText rangeOfString:@"." options:NSBackwardsSearch range:NSMakeRange(0, [inputText length])];
        int indexOfDot = aRange.location;
        //NSLog(@"aRange.location:%d - %d",aRange.location, indexOfDot);
        if(aRange.location != NSNotFound) {
            NSString *topLevelDomain = [inputText substringFromIndex:indexOfDot];
            topLevelDomain = [topLevelDomain lowercaseString];
            //NSLog(@"topleveldomains:%@",topLevelDomain);
            NSSet *TLD;
            TLD = [NSSet setWithObjects:@".aero", @".asia", @".biz", @".cat", @".com", @".coop", @".edu", @".gov", @".info", @".int", @".jobs", @".mil", @".mobi", @".museum", @".name", @".net", @".org", @".pro", @".tel", @".travel", @".ac", @".ad", @".ae", @".af", @".ag", @".ai", @".al", @".am", @".an", @".ao", @".aq", @".ar", @".as", @".at", @".au", @".aw", @".ax", @".az", @".ba", @".bb", @".bd", @".be", @".bf", @".bg", @".bh", @".bi", @".bj", @".bm", @".bn", @".bo", @".br", @".bs", @".bt", @".bv", @".bw", @".by", @".bz", @".ca", @".cc", @".cd", @".cf", @".cg", @".ch", @".ci", @".ck", @".cl", @".cm", @".cn", @".co", @".cr", @".cu", @".cv", @".cx", @".cy", @".cz", @".de", @".dj", @".dk", @".dm", @".do", @".dz", @".ec", @".ee", @".eg", @".er", @".es", @".et", @".eu", @".fi", @".fj", @".fk", @".fm", @".fo", @".fr", @".ga", @".gb", @".gd", @".ge", @".gf", @".gg", @".gh", @".gi", @".gl", @".gm", @".gn", @".gp", @".gq", @".gr", @".gs", @".gt", @".gu", @".gw", @".gy", @".hk", @".hm", @".hn", @".hr", @".ht", @".hu", @".id", @".ie", @" No", @".il", @".im", @".in", @".io", @".iq", @".ir", @".is", @".it", @".je", @".jm", @".jo", @".jp", @".ke", @".kg", @".kh", @".ki", @".km", @".kn", @".kp", @".kr", @".kw", @".ky", @".kz", @".la", @".lb", @".lc", @".li", @".lk", @".lr", @".ls", @".lt", @".lu", @".lv", @".ly", @".ma", @".mc", @".md", @".me", @".mg", @".mh", @".mk", @".ml", @".mm", @".mn", @".mo", @".mp", @".mq", @".mr", @".ms", @".mt", @".mu", @".mv", @".mw", @".mx", @".my", @".mz", @".na", @".nc", @".ne", @".nf", @".ng", @".ni", @".nl", @".no", @".np", @".nr", @".nu", @".nz", @".om", @".pa", @".pe", @".pf", @".pg", @".ph", @".pk", @".pl", @".pm", @".pn", @".pr", @".ps", @".pt", @".pw", @".py", @".qa", @".re", @".ro", @".rs", @".ru", @".rw", @".sa", @".sb", @".sc", @".sd", @".se", @".sg", @".sh", @".si", @".sj", @".sk", @".sl", @".sm", @".sn", @".so", @".sr", @".st", @".su", @".sv", @".sy", @".sz", @".tc", @".td", @".tf", @".tg", @".th", @".tj", @".tk", @".tl", @".tm", @".tn", @".to", @".tp", @".tr", @".tt", @".tv", @".tw", @".tz", @".ua", @".ug", @".uk", @".us", @".uy", @".uz", @".va", @".vc", @".ve", @".vg", @".vi", @".vn", @".vu", @".wf", @".ws", @".ye", @".yt", @".za", @".zm", @".zw", nil];
            if(topLevelDomain != nil && ([TLD containsObject:topLevelDomain])) {
                //NSLog(@"TLD contains topLevelDomain:%@",topLevelDomain);
                return TRUE;
            }
            /*else {
             NSLog(@"TLD DOEST NOT contains topLevelDomain:%@",topLevelDomain);
             }*/

        }
    }
    return FALSE;
}

SNR
  • 1,249
  • 2
  • 20
  • 38
  • 1
    There ist the string @" No" in your set of top-level domains. I think that should not be there. Also, your list is missing some official top-level domains, e.g. non-latin ones. See https://www.iana.org/domains/root/db for the official IANA list. – Florian May 14 '13 at 08:42
  • 1
    @Florian: `.no` is a valid TLD. It is used a lot in Norway. It is even listed in the resource you linked to. E.g: [www.google.no](http://www.google.no) – matsr Nov 08 '13 at 09:32
  • 1
    I am not talking about @".no", but @"No". It's right after @".ie" in the list. – Florian Nov 09 '13 at 10:46
  • 4
    This is not a good idea, this is already outdated as the .bike and .ventures TDL and thousands of others are already on sale. – jturolla Feb 11 '14 at 13:45
  • 1
    great answer ...tnx a lot @SNR – Ankur Kathiriya Oct 05 '15 at 09:13
12

Use the below code:-

NSString *emailRegEx = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegEx];
//Valid email address

if ([emailTest evaluateWithObject:userMailTextField.text] == YES) 
{
     //Do Something
}
else
{
     NSLog(@"email not in proper format");
}

userMailTextField is the name of my textField (use your own).

I hope this code will help you!!!

Naeem
  • 789
  • 1
  • 10
  • 23
Gypsa
  • 11,230
  • 6
  • 44
  • 82
11

Use Below code for "Swift language" For Email Validation

func ValidateEmailString (strEmail:NSString) -> Bool
{
   let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
   let emailText = NSPredicate(format:"SELF MATCHES [c]%@",emailRegex)
   return (emailText.evaluate(with: strEmail))
} 

Thanks :)

Abdul Saleem
  • 10,098
  • 5
  • 45
  • 45
Ilesh P
  • 3,940
  • 1
  • 24
  • 49
9

NSRegularExpression is the Best Way to Validate Email Addresses with iOS 4.x and Later.

-(BOOL) validateEmail:(NSString*) emailString 
{
     NSString *regExPattern = @"^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}$";
     NSRegularExpression *regEx = [[NSRegularExpression alloc] initWithPattern:regExPattern options:NSRegularExpressionCaseInsensitive error:nil];
     NSUInteger regExMatches = [regEx numberOfMatchesInString:emailString options:0 range:NSMakeRange(0, [emailString length])];
     NSLog(@"%i", regExMatches);
     if (regExMatches == 0) {
         return NO;
     } 
     else
         return YES;
}

Usage :

if([self validateEmail:@"something@domain.com"]) {
  //Email Address is valid.
} 
else {
  //Email Address is invalid.
}
Bhavin
  • 27,155
  • 11
  • 55
  • 94
2

--it's easy to validate your email id by calling validateEmail method:

-(BOOL)validateEmail:(NSString *)email      
{
    NSString *emailRegex = @"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?";  

    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];

    return [emailTest evaluateWithObject:email];
}

Verify your email id here....

BOOL eb=[self validateEmail:**youremailtextfield**];

if(!eb)
{
    UIAlertView *alertsuccess = [[UIAlertView alloc] initWithTitle:@"Sorry" message:@"Please enter correct email id"
                                                          delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];

    [alertsuccess show];
    [alertsuccess release]; 
}
Naeem
  • 789
  • 1
  • 10
  • 23
shankar
  • 239
  • 3
  • 5
2
- (BOOL)validateEmailAddress:(NSString*)yourEmail
{
    //create a regex string which includes all email validation
    NSString *emailRegex    = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";

    //create predicate with format matching your regex string
    NSPredicate *email  = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];

    //return True if your email address matches the predicate just formed 
    return [email evaluateWithObject:yourEmail];`
}
viral
  • 4,168
  • 5
  • 43
  • 68
Anil
  • 1,028
  • 9
  • 20
1

Here the simple way to validate email in obj c

if(![self validEmail:self.emailTxtFld.text]) {
    // here show alert not a valid email id
}

here valid email id method is

- (BOOL) validEmail:(NSString*) emailString {
if([emailString length]==0){
    return NO;
}
NSString *regExPattern = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSRegularExpression *regEx = [[NSRegularExpression alloc] initWithPattern:regExPattern options:NSRegularExpressionCaseInsensitive error:nil];
NSUInteger regExMatches = [regEx numberOfMatchesInString:emailString options:0 range:NSMakeRange(0, [emailString length])];
     if (regExMatches == 0) {
         return NO;
     } else {
             return YES;
       }
}

In Swift 3.0 Version

if !validEmailId(inputText: userNameTxtFld.text!)  {
        print("Not Valid Emaild")
    }
else {
    print("valid email id")
}    

func validEmailId(inputText: String)-> Bool {
    print("validate emilId: \(inputText)")
    let emailRegEx = "^(?:(?:(?:(?: )*(?:(?:(?:\\t| )*\\r\\n)?(?:\\t| )+))+(?: )*)|(?: )+)?(?:(?:(?:[-A-Za-z0-9!#$%&’*+/=?^_'{|}~]+(?:\\.[-A-Za-z0-9!#$%&’*+/=?^_'{|}~]+)*)|(?:\"(?:(?:(?:(?: )*(?:(?:[!#-Z^-~]|\\[|\\])|(?:\\\\(?:\\t|[ -~]))))+(?: )*)|(?: )+)\"))(?:@)(?:(?:(?:[A-Za-z0-9](?:[-A-Za-z0-9]{0,61}[A-Za-z0-9])?)(?:\\.[A-Za-z0-9](?:[-A-Za-z0-9]{0,61}[A-Za-z0-9])?)*)|(?:\\[(?:(?:(?:(?:(?:[0-9]|(?:[1-9][0-9])|(?:1[0-9][0-9])|(?:2[0-4][0-9])|(?:25[0-5]))\\.){3}(?:[0-9]|(?:[1-9][0-9])|(?:1[0-9][0-9])|(?:2[0-4][0-9])|(?:25[0-5]))))|(?:(?:(?: )*[!-Z^-~])*(?: )*)|(?:[Vv][0-9A-Fa-f]+\\.[-A-Za-z0-9._~!$&'()*+,;=:]+))\\])))(?:(?:(?:(?: )*(?:(?:(?:\\t| )*\\r\\n)?(?:\\t| )+))+(?: )*)|(?: )+)?$"
    let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
    let result = emailTest.evaluate(with: inputText)
    return result
}
User558
  • 1,165
  • 1
  • 13
  • 37
0

This works exactly

-(BOOL) emailValidation:(NSString *)emailTxt
{
    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:emailTxt];

}
kleopatra
  • 51,061
  • 28
  • 99
  • 211
0

perfect validation for email. try this.

- (BOOL)validateEmailWithString:(NSString*)checkString
{

    NSString *laxString = @".+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", laxString];
    return [emailTest evaluateWithObject:checkString];
}
Patel Jigar
  • 2,141
  • 1
  • 23
  • 30
0

Swift

func validateEmail(email:String) -> Bool {

    let stricterFilter = false
    let stricterFilterString = "[A-Z0-9a-z\\._%+-]+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}"
    let laxString = ".+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*";
    let emailRegex = stricterFilter ? stricterFilterString : laxString
    let emailTest = NSPredicate(format: "SELF MATCHES %@", emailRegex)

    return emailTest.evaluate(with: email);
}
tier777
  • 1,005
  • 12
  • 11
0

Function:

- (BOOL)validateEmail:(NSString *)enteredEmailID
{
    //checking valid email id or not
    NSString *emailReg = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailReg];
    return [emailTest evaluateWithObject:enteredEmailID];
}

Call it like:

if ([self validateEmail: textField.text])
        {
            //NSLog(@"Valid Email");
        }
        else
        {
            //NSLog(@"Invalid Email");
        }

EDIT: You can do this into textfield did end editing delegates or textfield should character change delegates

Raj Aryan
  • 363
  • 2
  • 15
0

A version using NSRegularExpression and regex pattern copied from OWASP_Validation_Regex_Repository

+ (BOOL) isValidEmail:(NSString *)emailString {
        NSError *error = NULL;
        /**
         * @see <a href="https://www.owasp.org/index.php/OWASP_Validation_Regex_Repository">OWASP_Validation_Regex_Repository</a>
         */
        NSString *emailPattern = @"^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";
        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:emailPattern
                                                                               options:NSRegularExpressionCaseInsensitive
                                                                                 error:&error];
        NSUInteger matchCount = [regex numberOfMatchesInString:emailString options:0 range:NSMakeRange(0, [emailString length])];
        return matchCount > 0;
    }
Codingpan
  • 318
  • 2
  • 6