验证具有特殊字符的文本字段

时间:2012-04-18 07:40:37

标签: iphone objective-c cocoa-touch ios4

在我的应用中。我想用特殊字符验证文本字段,

实施例。 如果用户按下?从键盘比用户无法进入?在Textfield,

请任何人建议,我该怎么做?

3 个答案:

答案 0 :(得分:5)

尝试下面它会帮助你。它只接受字母

   - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
    {
        //For avoiding user to enter non digital number..
        if([[string stringByTrimmingCharactersInSet:[[NSCharacterSet letterCharacterSet] invertedSet]] isEqualToString:@""])
        {
            return NO;
        }
        else
        {
            return YES;
        }
    }

答案 1 :(得分:0)

检查this

使用

- (BOOL) textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString*)textEntered

答案 2 :(得分:0)

看看是否有效:

    -(NSString *) formatIdentificationNumber:(NSString *)string
     {
       NSCharacterSet * invalidNumberSet = [NSCharacterSet characterSetWithCharactersInString:@"\n_!@#$%^&*()[]{}'\".,<>:;|\\/?+=\t~` "];

    NSString  * result  = @"";
    NSScanner * scanner = [NSScanner scannerWithString:string];
    NSString  * scannerResult;

    [scanner setCharactersToBeSkipped:nil];

     while (![scanner isAtEnd])
     {
    if([scanner scanUpToCharactersFromSet:invalidNumberSet intoString:&scannerResult])
    {
        result = [result stringByAppendingString:scannerResult];
    }
    else
    {
        if(![scanner isAtEnd])
        {
            [scanner setScanLocation:[scanner scanLocation]+1];
        }
    }
 }

  return result;
  }