Reputation: 9811
I'm trouble with check the Characters(a-z,A-Z) and special characters except(.) in NSString. I have a UITextField for Price, i need to pass the value for Price only Numbers with "."[Ex: Price :- 20.00]. I need to check whether any letters,special characters are in NSString, If the Characters,special characters are in NSString (UITextField text), i need to alert the user to enter valid numbers for the Field "Price.". Please help to solve this problem. Any suggestion/idea would be great. Thanks in advance.
Upvotes: 2
Views: 2190
Reputation: 6413
You can try to use NSScanner class with it's scanFloat method.
NSScanner *scanner = [NSScanner scannerWithString: theString];
float scannedValue = 0.0f;
BOOL foundFloat = [scanner scanFloat:&scannedValue];
if (foundFloat && [scanner isAtEnd])
{
// scan was successful
}
else
{
// illegal characters were found
}
Upvotes: 1
Reputation: 15442
Here's one way:
if ([myString isMatchedByRegex:@"^(?:|0|[1-9]\\d*)(?:\\.\\d*)?$"]) {
// String is OK
}
Upvotes: 1
Reputation: 2707
You can do like this,
- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSCharacterSet *nonNumberSet = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789."] invertedSet];
//here u can alert the user by checking length
return ([string stringByTrimmingCharactersInSet:nonNumberSet].length > 0);
}
Upvotes: 1
Reputation: 81868
You can use NSCharacterSet
to find characters in strings:
NSCharacterSet *nonDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
BOOL containsNonDigitChars = [myString rangeOfCharacterFromSet:nonDigits].location == NSNotFound
Upvotes: 2