我正在使用以下代码进行电子邮件验证。如果电子邮件ID以数字开头,那么它不接受,我想接受 123a@asd.com 。请建议我。
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];
return [emailTest evaluateWithObject:emailID];
提前致谢
答案 0 :(得分:0)
NSString *mailreg=@"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate *mailtest=[NSPredicate predicateWithFormat:@"SELF MATCHES %@",mailreg];
[mailtest evaluateWithObject:checkString]
试试这个
答案 1 :(得分:0)
这是我的观察,检查可能是你正在添加空白,这就是为什么它没有正确验证它 - 正如@Petesh在评论中也提到 - 很好的解释人。
-(BOOL)validate:(NSString *)emailID {
BOOL stricterFilter = YES;
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:emailID];
}
-(void)validateEmails {
if ([self validate:@" 123a@asd.com"] == true) {
NSLog(@"true");
} else {
NSLog(@"false"); //Result
}
if ([self validate:@"123a@asd.com"] == true) {
NSLog(@"true"); //Result
} else {
NSLog(@"false");
}
if ([self validate:@"myemail@gmail.com"] == true) {
NSLog(@"true"); //Result
} else {
NSLog(@"false");
}
if ([self validate:@"my?email@gmail.com"] == true) {
NSLog(@"true");
} else {
NSLog(@"false"); //Result
}
}