it-swarm.com.de

E-Mail-Überprüfung für textField in iOS

Wie füge ich in iOS App die E-Mail-Überprüfung für UITextField hinzu?

41
ios

Verwenden Sie NSPredicate und Regex:

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

Für ein paar E-Mails, die durch ein Komma getrennt sind:

- (NSMutableArray*)validateEmailWithString:(NSString*)emails
{
    NSMutableArray *validEmails = [[NSMutableArray alloc] init];
    NSArray *emailArray = [emails componentsSeparatedByString:@","];
    for (NSString *email in emailArray)
    {
        NSString *emailRegex = @"[A-Z0-9a-z._%+-][email protected][A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"; 
        NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex]; 
        if ([emailTest evaluateWithObject:email])
            [validEmails addObject:email];
    }
    return [validEmails autorelease];
}

Antwort bearbeitet: (Es werden auch zusätzliche Punkte geprüft.)

- (BOOL)validateEmailWithString:(NSString*)checkString
{
    BOOL stricterFilter = NO; // Discussion http://blog.logichigh.com/2010/09/02/validating-an-e-mail-address/
    NSString *stricterFilterString = @"[A-Z0-9a-z\\._%+-][email protected]([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}";
    NSString *laxString = @"[email protected]([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*";
    NSString *emailRegex = stricterFilter ? stricterFilterString : laxString;
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:checkString];
}
139
Rog

Probieren Sie es aus 
Dies überprüft genau die Domänennamen der obersten Ebene zusammen mit der Validierung.


- (BOOL)validateEmail:(NSString *)inputText {
    NSString *emailRegex = @"[A-Z0-9a-z][A-Z0-9a-z._%+-]*@[A-Za-z0-9][A-Za-z0-9.-]*\\.[A-Za-z]{2,6}"; 
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex]; 
    NSRange aRange;
    if([emailTest evaluateWithObject:inputText]) {
        aRange = [inputText rangeOfString:@"." options:NSBackwardsSearch range:NSMakeRange(0, [inputText length])];
        int indexOfDot = aRange.location;
        //NSLog(@"aRange.location:%d - %d",aRange.location, indexOfDot);
        if(aRange.location != NSNotFound) {
            NSString *topLevelDomain = [inputText substringFromIndex:indexOfDot];
            topLevelDomain = [topLevelDomain lowercaseString];
            //NSLog(@"topleveldomains:%@",topLevelDomain);
            NSSet *TLD;
            TLD = [NSSet setWithObjects:@".aero", @".asia", @".biz", @".cat", @".com", @".coop", @".edu", @".gov", @".info", @".int", @".jobs", @".mil", @".mobi", @".museum", @".name", @".net", @".org", @".pro", @".tel", @".travel", @".ac", @".ad", @".ae", @".af", @".ag", @".ai", @".al", @".am", @".an", @".ao", @".aq", @".ar", @".as", @".at", @".au", @".aw", @".ax", @".az", @".ba", @".bb", @".bd", @".be", @".bf", @".bg", @".bh", @".bi", @".bj", @".bm", @".bn", @".bo", @".br", @".bs", @".bt", @".bv", @".bw", @".by", @".bz", @".ca", @".cc", @".cd", @".cf", @".cg", @".ch", @".ci", @".ck", @".cl", @".cm", @".cn", @".co", @".cr", @".cu", @".cv", @".cx", @".cy", @".cz", @".de", @".dj", @".dk", @".dm", @".do", @".dz", @".ec", @".ee", @".eg", @".er", @".es", @".et", @".eu", @".fi", @".fj", @".fk", @".fm", @".fo", @".fr", @".ga", @".gb", @".Gd", @".ge", @".gf", @".gg", @".gh", @".gi", @".gl", @".gm", @".gn", @".gp", @".gq", @".gr", @".gs", @".gt", @".gu", @".gw", @".gy", @".hk", @".hm", @".hn", @".hr", @".ht", @".hu", @".id", @".ie", @" No", @".il", @".im", @".in", @".io", @".iq", @".ir", @".is", @".it", @".je", @".jm", @".jo", @".jp", @".ke", @".kg", @".kh", @".ki", @".km", @".kn", @".kp", @".kr", @".kw", @".ky", @".kz", @".la", @".lb", @".lc", @".li", @".lk", @".lr", @".ls", @".lt", @".lu", @".lv", @".ly", @".ma", @".mc", @".md", @".me", @".mg", @".mh", @".mk", @".ml", @".mm", @".mn", @".mo", @".mp", @".mq", @".mr", @".ms", @".mt", @".mu", @".mv", @".mw", @".mx", @".my", @".mz", @".na", @".nc", @".ne", @".nf", @".ng", @".ni", @".nl", @".no", @".np", @".nr", @".nu", @".nz", @".om", @".pa", @".pe", @".pf", @".pg", @".ph", @".pk", @".pl", @".pm", @".pn", @".pr", @".ps", @".pt", @".pw", @".py", @".qa", @".re", @".ro", @".rs", @".ru", @".rw", @".sa", @".sb", @".sc", @".sd", @".se", @".sg", @".sh", @".si", @".sj", @".sk", @".sl", @".sm", @".sn", @".so", @".sr", @".st", @".su", @".sv", @".sy", @".sz", @".tc", @".td", @".tf", @".tg", @".th", @".tj", @".tk", @".tl", @".tm", @".tn", @".to", @".tp", @".tr", @".tt", @".tv", @".tw", @".tz", @".ua", @".ug", @".uk", @".us", @".uy", @".uz", @".va", @".vc", @".ve", @".vg", @".vi", @".vn", @".vu", @".wf", @".ws", @".ye", @".yt", @".za", @".zm", @".zw", nil];
            if(topLevelDomain != nil && ([TLD containsObject:topLevelDomain])) {
                //NSLog(@"TLD contains topLevelDomain:%@",topLevelDomain);
                return TRUE;
            }
            /*else {
             NSLog(@"TLD DOEST NOT contains topLevelDomain:%@",topLevelDomain);
             }*/

        }
    }
    return FALSE;
}

19
SNR

Verwenden Sie den folgenden Code: -

NSString *emailRegEx = @"[A-Z0-9a-z._%+-][email protected][A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegEx];
//Valid email address

if ([emailTest evaluateWithObject:userMailTextField.text] == YES) 
{
     //Do Something
}
else
{
     NSLog(@"email not in proper format");
}

userMailTextField ist der Name meines textFields (verwenden Sie Ihr eigenes).

Ich hoffe dieser Code wird dir helfen !!!

12
Gypsa

Verwenden Sie den folgenden Code für "Schnelle Sprache" Für E-Mail-Bestätigung 

func ValidateEmailString (strEmail:NSString) -> Bool
{
   let emailRegex = "[A-Z0-9a-z._%+-][email protected][A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
   let emailText = NSPredicate(format:"SELF MATCHES [c]%@",emailRegex)
    return (emailText!.evaluateWithObject(strEmail))
} 

Vielen Dank :)

9
Ilesh

NSRegularExpression ist der beste Weg zur Überprüfung von E-Mail-Adressen mit iOS 4.x und höher.

-(BOOL) validateEmail:(NSString*) emailString 
{
     NSString *regExPattern = @"^[A-Z0-9._%+-][email protected][A-Z0-9.-]+\\.[A-Z]{2,4}$";
     NSRegularExpression *regEx = [[NSRegularExpression alloc] initWithPattern:regExPattern options:NSRegularExpressionCaseInsensitive error:nil];
     NSUInteger regExMatches = [regEx numberOfMatchesInString:emailString options:0 range:NSMakeRange(0, [emailString length])];
     NSLog(@"%i", regExMatches);
     if (regExMatches == 0) {
         return NO;
     } 
     else
         return YES;
}

Verwendungszweck :

if([self validateEmail:@"[email protected]"]) {
  //Email Address is valid.
} 
else {
  //Email Address is invalid.
}
8
Bhavin

--ist einfach, Ihre E-Mail-ID zu überprüfen, indem Sie die validateEmail-Methode aufrufen:

-(BOOL)validateEmail:(NSString *)email      
{
    NSString *emailRegex = @"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?";  

    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];

    return [emailTest evaluateWithObject:email];
}

Überprüfe deine Email ID hier ...

BOOL eb=[self validateEmail:**youremailtextfield**];

if(!eb)
{
    UIAlertView *alertsuccess = [[UIAlertView alloc] initWithTitle:@"Sorry" message:@"Please enter correct email id"
                                                          delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];

    [alertsuccess show];
    [alertsuccess release]; 
}
2
shankar

Hier der einfache Weg, um E-Mails in obj zu überprüfen. C

if(![self validEmail:self.emailTxtFld.text]) {
    // here show alert not a valid email id
}

hier ist eine gültige E-Mail-ID-Methode

- (BOOL) validEmail:(NSString*) emailString {
if([emailString length]==0){
    return NO;
}
NSString *regExPattern = @"[A-Z0-9a-z._%+-][email protected][A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSRegularExpression *regEx = [[NSRegularExpression alloc] initWithPattern:regExPattern options:NSRegularExpressionCaseInsensitive error:nil];
NSUInteger regExMatches = [regEx numberOfMatchesInString:emailString options:0 range:NSMakeRange(0, [emailString length])];
     if (regExMatches == 0) {
         return NO;
     } else {
             return YES;
       }
}

In Swift 3.0 Version

if !validEmailId(inputText: userNameTxtFld.text!)  {
        print("Not Valid Emaild")
    }
else {
    print("valid email id")
}    

func validEmailId(inputText: String)-> Bool {
    print("validate emilId: \(inputText)")
    let emailRegEx = "^(?:(?:(?:(?: )*(?:(?:(?:\\t| )*\\r\\n)?(?:\\t| )+))+(?: )*)|(?: )+)?(?:(?:(?:[-A-Za-z0-9!#$%&’*+/=?^_'{|}~]+(?:\\.[-A-Za-z0-9!#$%&’*+/=?^_'{|}~]+)*)|(?:\"(?:(?:(?:(?: )*(?:(?:[!#-Z^-~]|\\[|\\])|(?:\\\\(?:\\t|[ -~]))))+(?: )*)|(?: )+)\"))(?:@)(?:(?:(?:[A-Za-z0-9](?:[-A-Za-z0-9]{0,61}[A-Za-z0-9])?)(?:\\.[A-Za-z0-9](?:[-A-Za-z0-9]{0,61}[A-Za-z0-9])?)*)|(?:\\[(?:(?:(?:(?:(?:[0-9]|(?:[1-9][0-9])|(?:1[0-9][0-9])|(?:2[0-4][0-9])|(?:25[0-5]))\\.){3}(?:[0-9]|(?:[1-9][0-9])|(?:1[0-9][0-9])|(?:2[0-4][0-9])|(?:25[0-5]))))|(?:(?:(?: )*[!-Z^-~])*(?: )*)|(?:[Vv][0-9A-Fa-f]+\\.[-A-Za-z0-9._~!$&'()*+,;=:]+))\\])))(?:(?:(?:(?: )*(?:(?:(?:\\t| )*\\r\\n)?(?:\\t| )+))+(?: )*)|(?: )+)?$"
    let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
    let result = emailTest.evaluate(with: inputText)
    return result
}
1
User558
- (BOOL)validateEmailAddress:(NSString*)yourEmail
{
    //create a regex string which includes all email validation
    NSString *emailRegex    = @"[A-Z0-9a-z._%+-][email protected][A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";

    //create predicate with format matching your regex string
    NSPredicate *email  = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];

    //return True if your email address matches the predicate just formed 
    return [email evaluateWithObject:yourEmail];`
}
1
Anil

Swift

func validateEmail(email:String) -> Bool {

    let stricterFilter = false
    let stricterFilterString = "[A-Z0-9a-z\\._%+-][email protected]([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}"
    let laxString = "[email protected]([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*";
    let emailRegex = stricterFilter ? stricterFilterString : laxString
    let emailTest = NSPredicate(format: "SELF MATCHES %@", emailRegex)

    return emailTest.evaluate(with: email);
}
0
tier777

Das funktioniert genau

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

}

Ich bin Autor von DCKit library, der DCMandatoryEmailTextField hat. Diese Klasse führt die E-Mail-Validierung automatisch durch und hebt/hebt das Textfeld hervor, wenn der Benutzer einen Wert eingibt:

 DCKit: email validation text field

Check it out: https://github.com/andrew8712/DCKit

0
Andrey Gordeev

perfekte validierung für email. Versuche dies.

- (BOOL)validateEmailWithString:(NSString*)checkString
{

    NSString *laxString = @"[email protected]([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", laxString];
    return [emailTest evaluateWithObject:checkString];
}
0
Patel Jigar

Funktion:

- (BOOL)validateEmail:(NSString *)enteredEmailID
{
    //checking valid email id or not
    NSString *emailReg = @"[A-Z0-9a-z._%+-][email protected][A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailReg];
    return [emailTest evaluateWithObject:enteredEmailID];
}

Nenne es wie:  

if ([self validateEmail: textField.text])
        {
            //NSLog(@"Valid Email");
        }
        else
        {
            //NSLog(@"Invalid Email");
        }

EDIT: Sie können dies in ein Textfeld tun. Beenden Sie die Bearbeitung von Delegaten oder das Textfeld, wenn Sie Zeichenänderungen vornehmen

0
Raj Aryan