8

Possible Duplicate:
Ensure User has entered email address string in correct format?

I have UITextField in which I take the email address from user that they enter, and I want to validate that email address, such as I would it should check that it contains symbols like @ sign and other email characters.

If there is an error in the email address then it should show a UIAlertView that would say "enter a valid email address".

Community
  • 1
  • 1
Nazia Jan
  • 783
  • 3
  • 13
  • 19

3 Answers3

22

Objective C Style

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

if ([emailTest evaluateWithObject:email.text] == NO) {

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Test!" message:@"Please Enter Valid Email Address." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
    [alert release];

    return;
}

Swift Style

class func isValidEmail(emailString:String) -> Bool {

    let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,10}"
    var emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)

    let result = emailTest?.evaluateWithObject(emailString)
    return result!
}
Gergely Orosz
  • 6,475
  • 4
  • 47
  • 59
Sameera Chathuranga
  • 3,638
  • 3
  • 27
  • 48
3

You can do this using NSPredicate

//suppose emailID is your entered email address NSString
NSString *emailFormat1 = @"[A-Z0-9a-z._]+@[A-Za-z0-9]+\\.[A-Za-z]{2,4}";     


NSPredicate *emailTest1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailFormat1]; 


if ([emailTest1 evaluateWithObject:emailID]||[emailTest2 evaluateWithObject:emailID]) {
   //yes it is valid
}
else
    //no it is invalid
Neo
  • 2,807
  • 1
  • 16
  • 18
1

Add RegexKitLite to the project and find the solutions below.

  1. Best practices for validating email address in Objective-C on iOS 2.0
  2. How to validate email field in uitextfield in iphone
Community
  • 1
  • 1
iOS
  • 3,526
  • 3
  • 37
  • 82