如何仅在iOS中验证长度并将文本字段限制为数字,字母数字和字母字符

时间:2012-02-03 05:02:04

标签: ios

我想验证长度并仅在iOS中限制数字,字母数字和字母字符,任何人都可以帮助我实现此目的。

2 个答案:

答案 0 :(得分:3)

您可以形成正则表达式字符串并使用它。请在下面找一个代码示例,只允许使用字母和空格。

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString *stringPlace = @"[a-z  A-Z]*";
    NSPredicate *testPlace = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", stringPlace]; 
    BOOL matches = [testPlace evaluateWithObject:string];

    // if it does not match the regular expression and more than 5 characters 
    if (!matches && string.length > 5)
    {
        return NO;
    }
    return YES;
}

答案 1 :(得分:0)

找到解决这个问题的最佳方法。像冠军一样工作:)

在.m文件中

//#define CHARACTERS @" ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"

//#define CHARACTERS_NUMBERS  [CHARACTERS stringByAppendingString:@"1234567890"]
///// Inside shouldChangeCharactersInRange 

///////////>>>>>>>>>>>>>>>>>> 

if(textField== txtFldAlpha)
    {

        //Alpha only

        NSUInteger newLength = [textField.text length] + [string length] - range.length;

        NSCharacterSet *unacceptedInput =
        [[NSCharacterSet characterSetWithCharactersInString:CHARACTERS] invertedSet];

        // Create array of strings from incoming string using the unacceptable
        // characters as the trigger of where to split the string.
        // If array has more than one entry, there was at least one unacceptable character
        if ([[string componentsSeparatedByCharactersInSet:unacceptedInput] count] > 1)
            return NO;
        else 
            return YES&&(newLength < 26);
        return YES;
    }

///////////<<<<<<<<<<<<<<<<<<

///////////>>>>>>>>>>>>>>>>>>

if(textField==txtFldNumeric)
    {
        //Num only

        NSUInteger newLength = [textField.text length] + [string length] - range.length;
        NSCharacterSet *nonNumberSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];

        if ([[string componentsSeparatedByCharactersInSet:nonNumberSet] count] > 1)
            return NO;
        else 
            return YES&&(newLength < 6);
        return YES;

    }

///////////<<<<<<<<<<<<<<<<<<

///////////>>>>>>>>>>>>>>>>>>

if(textField==txtFieldNumAlphaSpecial)
    {
        //Num,Alpha,Special field

        NSUInteger newLength = [textField.text length] + [string length] - range.length;
        return (newLength > 50) ? NO : YES;
    }    
///////////<<<<<<<<<<<<<<<<<<