objective-c 检查 UITextField 的输入是否仅为数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1320295/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 22:07:33  来源:igfitidea点击:

Check that a input to UITextField is numeric only

objective-ccocoa-touchvalidationnsstringuitextfield

提问by g.revolution

How do I validate the string input to a UITextField? I want to check that the string is numeric, including decimal points.

如何验证输入到 a 的字符串UITextField?我想检查字符串是否为数字,包括小数点。

采纳答案by Peter N Lewis

I use this code in my Mac app, the same or similar should work with the iPhone. It's based on the RegexKitLite regular expressions and turns the text red when its invalid.

我在我的 Mac 应用程序中使用此代码,相同或相似的代码应该适用于 iPhone。它基于 RegexKitLite 正则表达式,并在其无效时将文本变为红色。

static bool TextIsValidValue( NSString* newText, double &value )
{
    bool result = false;

    if ( [newText isMatchedByRegex:@"^(?:|0|[1-9]\d*)(?:\.\d*)?$"] ) {
        result = true;
        value = [newText doubleValue];
    }
    return result;
}

- (IBAction) doTextChanged:(id)sender;
{
    double value;
    if ( TextIsValidValue( [i_pause stringValue], value ) ) {
        [i_pause setTextColor:[NSColor blackColor]];
        // do something with the value
    } else {
        [i_pause setTextColor:[NSColor redColor]];
    }
}

回答by Donal O'Danachair

You can do it in a few lines like this:

你可以用这样的几行来完成:

BOOL valid;
NSCharacterSet *alphaNums = [NSCharacterSet decimalDigitCharacterSet];
NSCharacterSet *inStringSet = [NSCharacterSet characterSetWithCharactersInString:myInputField.text];
valid = [alphaNums isSupersetOfSet:inStringSet];    
if (!valid) // Not numeric

-- this is for validating input is numeric chars only. Look at the documentation for NSCharacterSetfor the other options. You can use characterSetWithCharactersInString to specify any set of valid input characters.

-- 这仅用于验证输入是否为数字字符。查看NSCharacterSet其他选项的文档。您可以使用 characterSetWithCharactersInString 来指定任何一组有效的输入字符。

回答by Dave DeLong

There are a few ways you could do this:

有几种方法可以做到这一点:

  1. Use NSNumberFormatter's numberFromString: method. This will return an NSNumber if it can parse the string correctly, or nilif it cannot.
  2. Use NSScanner
  3. Strip any non-numeric character and see if the string still matches
  4. Use a regular expression
  1. 使用 NSNumberFormatter 的 numberFromString: 方法。如果它可以正确解析字符串,或者nil不能正确解析,这将返回一个 NSNumber 。
  2. 使用 NSScanner
  3. 去除任何非数字字符并查看字符串是否仍然匹配
  4. 使用正则表达式

IMO, using something like -[NSString doubleValue]wouldn't be the best option because both @"0.0"and @"abc"will have a doubleValue of 0. The *value methods all return 0 if they're not able to convert the string properly, so it would be difficult to distinguish between a legitimate string of @"0"and a non-valid string. Something like C's strtolfunction would have the same issue.

IMO,使用类似-[NSString doubleValue]将不会是最好的选择,因为两者@"0.0"@"abc"会产生的doubleValue 0的*值的方法都返回0,如果他们不能将字符串正确转换,所以这将是一个很难区分合法字符串@"0"和无效字符串。像 C 的strtol函数一样会有同样的问题。

I think using NSNumberFormatter would be the best option, since it takes locale into account (ie, the number @"1,23"in Europe, versus @"1.23"in the USA).

我认为使用 NSNumberFormatter 将是最好的选择,因为它考虑了语言环境(即@"1,23"欧洲的数字与@"1.23"美国的数字)。

回答by Frank Shearar

If you want a user to only be allowed to enter numerals, you can make your ViewController implement part of UITextFieldDelegate and define this method:

如果你希望用户只被允许输入数字,你可以让你的 ViewController 实现 UITextFieldDelegate 的一部分并定义这个方法:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
  NSString *resultingString = [textField.text stringByReplacingCharactersInRange: range withString: string];

  // The user deleting all input is perfectly acceptable.
  if ([resultingString length] == 0) {
    return true;
  }

  NSInteger holder;

  NSScanner *scan = [NSScanner scannerWithString: resultingString];

  return [scan scanInteger: &holder] && [scan isAtEnd];
}

There are probably more efficient ways, but I find this a pretty convenientway. And the method should be readily adaptable to validating doubles or whatever: just use scanDouble: or similar.

可能有更有效的方法,但我发现这是一种非常方便的方法。并且该方法应该很容易适应验证双打或其他:只需使用 scanDouble: 或类似的。

回答by kalpesh jetani

#pragma mark - UItextfield Delegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if ([string isEqualToString:@"("]||[string isEqualToString:@")"]) {
        return TRUE;
    }

    NSLog(@"Range ==%d  ,%d",range.length,range.location);
    //NSRange *CURRANGE = [NSString  rangeOfString:string];

    if (range.location == 0 && range.length == 0) {
        if ([string isEqualToString:@"+"]) {
            return TRUE;
        }
    }
    return [self isNumeric:string];
}

-(BOOL)isNumeric:(NSString*)inputString{
    BOOL isValid = NO;
    NSCharacterSet *alphaNumbersSet = [NSCharacterSet decimalDigitCharacterSet];
    NSCharacterSet *stringSet = [NSCharacterSet characterSetWithCharactersInString:inputString];
    isValid = [alphaNumbersSet isSupersetOfSet:stringSet];
    return isValid;
}

回答by Sai Ramachandran

Here are a few one-liners which combine Peter Lewis' answer above (Check that a input to UITextField is numeric only) with NSPredicates

这里有一些单行代码,它们结合了上面 Peter Lewis 的回答(检查 UITextField 的输入是否仅为数字)和 NSPredicates

    #define REGEX_FOR_NUMBERS   @"^([+-]?)(?:|0|[1-9]\d*)(?:\.\d*)?$"
    #define REGEX_FOR_INTEGERS  @"^([+-]?)(?:|0|[1-9]\d*)?$"
    #define IS_A_NUMBER(string) [[NSPredicate predicateWithFormat:@"SELF MATCHES %@", REGEX_FOR_NUMBERS] evaluateWithObject:string]
    #define IS_AN_INTEGER(string) [[NSPredicate predicateWithFormat:@"SELF MATCHES %@", REGEX_FOR_INTEGERS] evaluateWithObject:string]

回答by zvjerka24

For integer test it'll be:

对于整数测试,它将是:

- (BOOL) isIntegerNumber: (NSString*)input
{
    return [input integerValue] != 0 || [input isEqualToString:@"0"];
}

回答by guptron

Hi had the exact same problem and I don't see the answer I used posted, so here it is.

嗨,有完全相同的问题,我没有看到我发布的答案,所以在这里。

I created and connected my text field via IB. When I connected it to my code via Control+Drag, I chose Action, then selected the Editing Changed event. This triggers the method on each character entry. You can use a different event to suit.

我通过 IB 创建并连接了我的文本字段。当我通过 Control+Drag 将它连接到我的代码时,我选择了 Action,然后选择了 Editing Changed 事件。这会在每个字符条目上触发该方法。您可以使用不同的事件来适应。

Afterwards, I used this simple code to replace the text. Note that I created my own character set to include the decimal/period character and numbers. Basically separates the string on the invalid characters, then rejoins them with empty string.

之后,我用这个简单的代码来替换文本。请注意,我创建了自己的字符集以包含小数/句点字符和数字。基本上将无效字符上的字符串分开,然后用空字符串重新连接它们。

- (IBAction)myTextFieldEditingChangedMethod:(UITextField *)sender {
        NSCharacterSet *validCharacterSet = [NSCharacterSet characterSetWithCharactersInString:@".0123456789"];
        NSCharacterSet *invalidCharacterSet = validCharacterSet.invertedSet;
        sender.text = [[sender.text componentsSeparatedByCharactersInSet:invalidCharacterSet] componentsJoinedByString:@""];
}

Credits: Remove all but numbers from NSString

积分: 从 NSString 中删除除数字以外的所有内容

回答by Hsm

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if(string.length > 0)
    {
        NSCharacterSet *numbersOnly = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
        NSCharacterSet *characterSetFromTextField = [NSCharacterSet characterSetWithCharactersInString:string];

        BOOL stringIsValid = [numbersOnly isSupersetOfSet:characterSetFromTextField];
        return stringIsValid;
    }
    return YES;
}

回答by David

IMO the best way to accomplish your goal is to display a numeric keyboard rather than the normal keyboard. This restricts which keys are available to the user. This alleviates the need to do validation, and more importantly it prevents the user from making a mistake. The number pad is also much nicer for entering numbers because the keys are substantially larger.

IMO 实现目标的最佳方式是显示数字键盘而不是普通键盘。这限制了用户可以使用哪些键。这减轻了进行验证的需要,更重要的是它可以防止用户犯错误。数字键盘也更适合输入数字,因为按键要大得多。

In interface builder select the UITextField, go to the Attributes Inspector and change the "Keyboard Type" to "Decimal Pad".

在界面构建器中选择 UITextField,转到 Attributes Inspector 并将“Keyboard Type”更改为“Decimal Pad”。

enter image description here

在此处输入图片说明

That'll make the keyboard look like this:

这将使键盘看起来像这样:

enter image description here

在此处输入图片说明

The only thing left to do is ensure the user doesn't enter in two decimal places. You can do this while they're editing. Add the following code to your view controller. This code removes a second decimal place as soon as it is entered. It appears to the user as if the 2nd decimal never appeared in the first place.

剩下要做的唯一一件事是确保用户不会输入两位小数。您可以在他们编辑时执行此操作。将以下代码添加到您的视图控制器。此代码在输入后立即删除第二个小数位。对用户来说,似乎第二位小数从未出现在第一位。

- (void)viewDidLoad
{
  [super viewDidLoad];

  [self.textField addTarget:self
                    action:@selector(textFieldDidChange:)
           forControlEvents:UIControlEventEditingChanged];
}

- (void)textFieldDidChange:(UITextField *)textField
{
  NSString *text = textField.text;
  NSRange range = [text rangeOfString:@"."];

  if (range.location != NSNotFound &&
      [text hasSuffix:@"."] &&
      range.location != (text.length - 1))
  {
    // There's more than one decimal
    textField.text = [text substringToIndex:text.length - 1];
  }
}