Please help with characterSetWithCharactersInString example

Discussion in 'iOS Programming' started by MTShipp, Jun 24, 2009.

  1. MTShipp macrumors 6502a

    Joined:
    Mar 25, 2009
    Location:
    Raleigh, North Carolina
    #1
    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?
     
  2. MTShipp thread starter macrumors 6502a

    Joined:
    Mar 25, 2009
    Location:
    Raleigh, North Carolina
    #2
    I found a different way to do it. And no, I won't show you. :p
     
  3. kainjow Moderator emeritus

    kainjow

    Joined:
    Jun 15, 2000
    #3
    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.
     
  4. Guiyon macrumors 6502a

    Joined:
    Mar 19, 2008
    Location:
    North Shore, MA
    #4
    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;
      }
     
  5. dejo Moderator

    dejo

    Staff Member

    Joined:
    Sep 2, 2004
    Location:
    The Centennial State
    #5
    Well, good luck with any future help then! :rolleyes:
     

Share This Page