UITextField只允许输入英文字母

时间:2013-03-13 17:14:43

标签: ios objective-c uitextfield character

我想将输入限制为只有英文字母(a-z)的用户名字段。有人可以帮我添加下面的代码,不允许输入除英文字母以外的任何数字,字符和任何其他语言吗?

现在,下面的代码不允许使用空格,也不允许输入超过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;
}

感谢。

1 个答案:

答案 0 :(得分:7)

您可以使用此正则表达式检查用户名是否仅包含英文字母:

NSString *nameRegex = @"[A-Za-z]+";
NSPredicate *nameTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", nameRegex];

if(![nameTest evaluateWithObject:self.usernameField.text]){
        self.title.text = @"Username can only contain english letters.";
        self.title.textColor = [UIColor yellowColor];

        _isAllowed =  NO;
}