Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate the email address in UITextField in iphone [duplicate]

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".

like image 502
Nazia Jan Avatar asked Sep 04 '12 08:09

Nazia Jan


1 Answers

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!
}
like image 104
Sameera Chathuranga Avatar answered Oct 04 '22 11:10

Sameera Chathuranga