iOS电子邮件地址验证不接受.in

时间:2016-03-10 05:10:29

标签: ios objective-c regex

使用正则表达式验证电子邮件地址,不接受两个字符扩展名,例如.in .co等

BOOL stricterFilter = NO;
NSString *stricterFilterString = @"^[A-Z0-9a-z\\._%+-]+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}$";
NSString *laxString = @"^.+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*$";
NSString *emailRegex = stricterFilter ? stricterFilterString : laxString;
NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];

4 个答案:

答案 0 :(得分:2)

使用此

#pragma mark - Valid Email
+ (BOOL)isValidEmail:(NSString*)email
{
    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:email];
}

答案 1 :(得分:1)

您只需要检查laxString,如下所示:

 NSString *laxString = @".+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*";

然后检查一定是否正常

以下是我的工作代码:

- (BOOL)validateEmailWithString:(NSString*)checkString
{
    NSString *stricterFilterString = @"[A-Z0-9a-z\\._%+-]+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}";
    NSString *laxString = @".+@([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];
}

答案 2 :(得分:0)

验证电子邮件usind以下功能

 - (BOOL)validateEmail:(NSString *)email
    {
        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:email];
    }

验证电子邮件后,请在电子邮件末尾检查 .in ,否则使用以下代码

NSString *lastThreeChar = [yourNewString substringFromIndex:[txt_Email.text length] - 3];
    if ([lastThreeChar isEqualToString:@".in"])
     {
      // email_id contain .in
     }
    else{
        // email_id dosen't contain .in
      }

答案 3 :(得分:0)

-(BOOL)validateEmail {
    //Email address field should give an error when the email address begins with ".","-","_" .
    // Works well with @me.com.

    NSString *emailRegex = @"[A-Z0-9a-z]([A-Z0-9a-z._-]{0,64})+[A-Z0-9a-z]+@[A-Z0-9a-z]+([A-Za-z0-9.-]{0,64})+([A-Z0-9a-z])+\\.[A-Za-z]{2,4}";
    NSPredicate *emailPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];   
    return ([emailPredicate evaluateWithObject:self.text] && self.text.length <= 64 && ([self.text rangeOfString:@".."].location == NSNotFound));
}