您好我想在用户在文本字段中输入文本时验证电子邮件地址。当错误的电子邮件然后显示警报并返回no留在电子邮件文本字段时,它正在返回和文本字段结束编辑但不在textField shouldChangeCharactersInRange上工作。 如果有人知道如何分享它,请提前致谢。 这是我的回复验证示例代码
- (void)textFieldDidEndEditing:(UITextField *)textField
{
activeTextfield=textField;
if(activeTextfield==txtCon1Email || activeTextfield==txtCon1SecondMail || activeTextfield==txtCon2Email || activeTextfield==txtCon2SecondMail)
{
NSString *emailReg = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailReg];
if ([emailTest evaluateWithObject:textField.text] == NO)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"OTS" message:@"Please enter valid email address." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
isvalidemail=NO;
}
else
isvalidemail=YES;
}
}
但我希望在用户输入文字时进行此操作
答案 0 :(得分:2)
这可能足以满足您的需求:只需尝试使用textFieldDidEndEditing
代理:
-(BOOL)textFieldShouldEndEditing:(UITextField *)textField{
if ([textField.text length]==0 || [self validateEmailWithString:textField.text]) {
[textField resignFirstResponder];
}else{
[[[UIAlertView alloc] initWithTitle:@"OTS" message:@"Please enter valid email address." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]show];
[textField becomeFirstResponder];
return NO;
}
return YES;
}
- (BOOL)validateEmailWithString:(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 :(得分:0)
如果您想使用shouldChangeCharactersInRange
方法,请注意每个最后添加的字符都在replacementString
中,其余的在输入新字符之前是textField.text
。
因此,在验证电子邮件时,您需要将textField.text和replacementString组合在一起,如下所示:
请记住,当您使用textField.text 时,您缺少最后一个字符,如果您使用replacementString ,则只会获得最后添加的字符。