2

我在联系人屏幕中有一个文本字段,用户需要输入电子邮件地址才能向我发送消息。确保用户输入有效电子邮件地址的最佳方法是什么,例如:

a@b.com / net / org / co.il
abc@gmail.com
abc@yahoo.com

ETC..

谢谢

4

3 回答 3

5

尝试以下操作:

- (BOOL) validateEmail: (NSString *) candidate {
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
//  return 0;
    return [emailTest evaluateWithObject:candidate];
}


-(IBAction)btnTapped:(id)sender{

    if([self validateEmail:[txtEmail text]] ==1)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Message" message:@"You Enter Correct Email id." delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alert show];
        [alert release];

    }
    else{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Message" message:@"You Enter Incoorect Email id." delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alert show];
        [alert release];
    }
}
于 2012-06-19T05:08:08.060 回答
2

使用这个 textField 委托函数,因为这将在每个输入的文本上调用:

 - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
 {
      NSString *strEnteredText = textField.text;
     if(strEnteredText.length>0) 
     {
       if([self validateEmail:strEnteredText])
       {
          //Valid email 
          //Use UILabel to give message
         // BOOL email = true to know email is valid when submit button tapped
       }
       else
       {
          //Not Valid email
          //Use UILabel to give message
          // BOOl emaiL = false to know email is valid when submit button tapped
        }
     }
 }

添加这个方法.h文件

 - (BOOL) validateEmail: (NSString *) enteredText 
 {
   NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"; 
   NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex]; 
   return [emailTest evaluateWithObject:enteredText];
 }
于 2012-06-19T05:16:55.610 回答
0

迅速

extension String {
    func isValidEmail() -> Bool {
        let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,10}"
        let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
        let result = emailTest.evaluateWithObject(self)
        return result
    }
}

"jim@off.com".isValidEmail() //true
"jim.com".isValidEmail() // false
于 2016-05-03T02:24:48.217 回答