Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

MTShipp

macrumors 6502a
Original poster
Mar 25, 2009
898
254
Raleigh, North Carolina
I am trying to write code to verify that my user only input numbers 0 through 9 and/or a decimal. I need to verify that data input into a text field is only a float (ex. 10.3)

I am a n00b but figure I'd have to use characterSetWithCharactersInString to verify the input.

SO far, this is what I have...yes, only this.

Code:
- (IBAction)buttonclick:(id)sender
{
	[textBox resignFirstResponder];
	NSCharacterSet *NumberSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789."];

Am I even on the right track or completely off base in doing this kind of verification? I started by only using the numpad keyboard but that does not allow the decimal so figured I would need to use a keyboard with more items but now, I don't want erroneous keys like '?' or 'm' etc.

I have no idea what to do to verify the data. Can you all assist?
 
A simple way to do it would be to just loop through each character in the input string via substringWithRange, and then check to see if that string exists in the string that contains the valid characters using rangeOfString.
 
Assuming your targeting 3.0 and depending on your performance concerns you could always use NSPredicate and a Regex (it's a bit heavyweight though...)

Quick & Dirty code below

Code:
  NSString    *regex = [[NSString alloc] initWithFormat:  @"SELF MATCHES '%@'", @"(\\\\d+)(.\\\\d+)+"];
  NSPredicate *regexPred = [NSPredicate predicateWithFormat: regex];
  NSString*   text = @"4.0";
  
  NSLog( @"Got format '%@' from '%@'", [regexPred predicateFormat], regex );
  [regex release];
  
  if( nil == regexPred ) {
    NSLog( @"Error: NIL predicate" );
    return 1;
  } else if( YES == [regexPred evaluateWithObject: text] ) {
    NSLog( @"'%@' is a valid decimal", text );
    [pool drain];
    return 0;
  } else {
    NSLog( @"'%@' is an invalid decimal", text );
    return 0;
  }
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.