可能重复:
Ensure User has entered email address string in correct format?
我有UITextField
我在其中输入用户输入的电子邮件地址,我想验证该电子邮件地址,例如我应该检查它是否包含@ sign和其他电子邮件字符等符号
如果电子邮件地址出错,则应显示UIAlertView
,表示“输入有效的电子邮件地址”。
答案 0 :(得分:22)
目标C风格
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!
}
答案 1 :(得分:3)
您可以使用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
答案 2 :(得分:1)