Ensure User has entered email address string in correct format?

半世苍凉 提交于 2019-11-30 19:00:32

问题


i have a text field in Contact screen and the user need to enter email address to send me message. Whats the best way to ensure the user has entered a valid email address such as:

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

etc..

Thanks


回答1:


Try the following:

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



回答2:


Use this textField delegate function as this will be called on every text entered:

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

Add this method .h file

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



回答3:


Swift

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


来源:https://stackoverflow.com/questions/11094658/ensure-user-has-entered-email-address-string-in-correct-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!