ios验证某些字符的文本字段输入

时间:2013-12-12 09:27:18

标签: ios validation uitextfield

我是ios开发的新手。在验证文本字段时,我必须确保它只包含0-9和特殊字符,如*和#。请帮帮我。

- (BOOL)validate:(NSString *)string{
    NSString *exp = @"^([0-9]+)?(\\.([0-9]{1,2})?)?$";
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:exp options:NSRegularExpressionCaseInsensitive error:nil];
    NSUInteger numberOfMatches = [regex numberOfMatchesInString:string options:0 range:NSMakeRange(0, [string length])];
    if (numberOfMatches == 0)
        return NO;
    return YES;
}

2 个答案:

答案 0 :(得分:1)

试试这个:

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

    NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789*#"] invertedSet];

    NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];

    return [string isEqualToString:filtered];
}

答案 1 :(得分:0)

你可以试试这个:

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

NSCharacterSet *numberAndSpecialCharsSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789*#"];

return ([string rangeOfCharacterFromSet:numberAndSpecialCharsSet].location==NSNotFound);

}