0

I have a UITextField where the user should type a float number. I want to check that such number has a certain format I receive, for instance "dddd.dd", where "d" is a digit. The format could change at any moment, since I receive it as input as well, so for example I may want to check at another moment that "," character is used for decimals, to say another example.

Taking into account that the text you read from the UITextField is of String type (optional), what should be the best way to accomplish this?

  • A predicate with the format provided. Then evaluate the input string. Then converting to number.
  • Try to convert to number. If success (how characters for separating decimals would be handled this way?), then check the format with NumberFormatter?
  • Any other and/or better way?
AppsDev
  • 12,319
  • 23
  • 93
  • 186
  • If you dont have so many formats try regular expression to validate the input base on situation then covert it to number. Like you suggested, the first way. – Mohammadalijf Dec 12 '16 at 17:22
  • are you willing to restrict users to not register anything other than number? – Saheb Roy Dec 12 '16 at 17:52
  • @SahebRoy yes, in such text field I only expect numbers (and thousands and decimal separators) – AppsDev Dec 12 '16 at 18:17
  • http://stackoverflow.com/questions/29782982/how-to-input-currency-format-on-a-text-field-from-right-to-left-using-swift/29783546?s=1|0.1074#29783546 – Leo Dabus Dec 12 '16 at 18:27

1 Answers1

1

Try this

in viewDidLoad or assign delegate to the textfield to self

-(void)viewDidLoad{
   self.txtFieldName.delegate = self;
}

Now implement this delegate method -

 -(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if(textField == self.txtFieldName)
    {
        NSCharacterSet *invalidCharSet = [[NSCharacterSet characterSetWithCharactersInString:@"01234567989."] invertedSet];
        NSString *filtered = [[string componentsSeparatedByCharactersInSet:invalidCharSet] componentsJoinedByString:@""];
        return [string isEqualToString:filtered];
    }
    else
        return YES;
}

This will enable yout textfield to only take numbers from 0-9 and .(decimal).

Saheb Roy
  • 5,899
  • 3
  • 23
  • 35