2012-09-04 63 views

回答

22

目標C風格

NSString *emailRegEx = @"[A-Z0-9a-z._%+-][email protected][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._%+-][email protected][A-Za-z0-9.-]+\\.[A-Za-z]{2,10}" 
    var emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx) 

    let result = emailTest?.evaluateWithObject(emailString) 
    return result! 
} 
3

可以使用NSPredicate

做到這一點
//suppose emailID is your entered email address NSString 
NSString *emailFormat1 = @"[A-Z0-9a-z._][email protected][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