2012-09-04 32 views
8

thể trùng lặp:
Ensure User has entered email address string in correct format?Validate địa chỉ email trong UITextField trong iphone

Tôi có UITextField trong đó tôi lấy địa chỉ email từ người dùng rằng họ nhập, và tôi muốn xác nhận địa chỉ email đó, chẳng hạn như tôi sẽ kiểm tra xem nó có chứa các ký hiệu như ký hiệu @ và các ký tự email khác không.

Nếu có lỗi trong địa chỉ email thì sẽ hiển thị số UIAlertView có thể là "nhập địa chỉ email hợp lệ".

Trả lời

22

Objective C Phong cách

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; 
} 

Kiểu Swift

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

Bạn có thể làm điều này bằng 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 
Các vấn đề liên quan