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!
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
}
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.