我想将用户名字段的输入限制为仅限英文字母(az)。有人可以帮我添加到下面的代码中,以不允许输入除英文字母之外的任何数字、字符和任何其他语言吗?
现在下面的代码不允许空格,也不允许输入超过 10 个字母。
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
{
BOOL _isAllowed = YES;
NSString *nameRegex = @"[A-Za-z]+";
NSPredicate *nameTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", nameRegex];
NSString *tempString = [[textField.text stringByReplacingCharactersInRange:range withString:string] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if (textField == self.usernameField)
{
if ([self.usernameField.text isEqualToString:tempString])
{
self.title.text = @"No Spaces Allowed";
self.title.textColor = [UIColor yellowColor];
_isAllowed = NO;
}
else if (tempString.length > 10)
{
self.title.text = @"Username cannot be more than 10 letters.";
self.title.textColor = [UIColor yellowColor];
_isAllowed = NO;
}
更新:
else if (![nameTest evaluateWithObject:self.usernameField.text])
{
self.title.text = @"Username can only contain english letters.";
self.title.textColor = [UIColor yellowColor];
_isAllowed = NO;
}
return _isAllowed;
}
return _isAllowed;
}
谢谢。