NSString Validation

孤街醉人 提交于 2019-12-12 02:47:34

问题


I need to validate some NSString that user inputs in some UITextField.

There are 2 kinds of validation I need.

1st, to judge whether a NSString object is a legal decimal number.

For example, @"100", @"10.1",@"0.11", are all legal, but @"100.11.1" is not.

2nd, to judge whether a NSString object is not a space-only string.

For example, @"abc", @"ab----c", are all legal, but @"-----", @"", are not.

here "-" means a space " ".

How can I validate these 2 kinds of NSString?

Thanks a lot!


回答1:


For the first part try this

NSNumberFormatter *formatter = [[[NSNumberFormatter alloc] init] autorelease];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setAllowsFloats:YES];
[formatter setDecimalSeparator:@"."];

NSNumber *number = [formatter numberFromString: inputString];

if(number == nil)
{
  //invalid input string
}

For the second part try this:

NSString *str = [inputString stringByReplacingOccurrencesOfString:@" " withString:@""];
if([str length] == 0)
{
    //invalid input string
}



回答2:


For the first validation you can count the decimal points. Zero is valid. Anything greater than one is invalid. And one is always valid (assuming ".123" is valid).

For the second validation you can compare the empty string @"" to the original string with all space(s) removed. If they're equal then your original string was invalid.

Search around SO. For example Number of Occurrences of a Character in NSString could be helpful.



来源:https://stackoverflow.com/questions/9286916/nsstring-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!