我正在注册过程中,我想确认用户提供的电子邮件是否存在并且尚未被接收。
到目前为止,我已经设置了正则表达式并根据需要对其进行了自定义(我将用户限制为学生电子邮件地址)。
- (BOOL)validateEmail:(NSString *)emailStr {
NSString *emailRegex = @"[A-Za-z]+\\.[A-Za-z]+@[ace]+\\.[tamut]+\\.[edu]";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
[self checkEmailAndDisplayAlert];
return [emailTest evaluateWithObject:emailStr];
}
如果电子邮件 Not Acceptable ,我会发出警报。
- (void)checkEmailAndDisplayAlert {
if(![self validateEmail:[_email text]]) {
[self.email becomeFirstResponder];
// user entered invalid email address
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Enter a valid email address." delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
[alert show];
} else {
// user entered valid email address
[self registerNewUser];
}
}
如果我输入的电子邮件不符合正则表达式要求,则不会显示正确的警报,我仍然可以作为新用户通过注册。我做错了什么?
请不要拒绝任何反馈,我是编程新手,这是我需要知道的,没有任何借口。
最佳答案
在您的 validateEmail
中方法,你调用checkEmailAndDisplayAlert
( [self checkEmailAndDisplayAlert];
),它还调用 validateEmail
。我会删除[self checkEmailAndDisplayAlert];
以避免无限循环。
此外,尝试将正则表达式更改为
NSString *emailRegex = @"^[A-Za-z]+\\.[A-Za-z]+@ace\\.tamut\\.edu$";
检查有效性的函数也可能如下所示:
- (BOOL)validateEmail:(NSString *)emailStr
{
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^[a-z]+\\.[a-z]+@ace\\.tamut\\.edu$" options:NSRegularExpressionCaseInsensitive error:&error];
NSAssert(regex, @"Unable to create regular expression");
NSRange txtRng = NSMakeRange(0, emailStr.length);
NSRange matchRng = [regex rangeOfFirstMatchInString:emailStr options:NSMatchingReportProgress range:txtRng];
BOOL validated = NO;
if (matchRng.location != NSNotFound)
validated = YES; // Match found
return validated;
}
^
和 $
添加在正则表达式模式的开头和结尾以启用整个字符串搜索。
关于ios - 使用 Parse 和 email Regex 确认电子邮件地址存在且未被占用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29175739/