Set a UITextField to write a maximum of 11 numbers using NSNumberFormatter

288 views Asked by At

i’m trying to configure a UITExtField to only accept 11 numbers, i’m using NSNumberFormatter and it works just fine with using numbers, but when I try to set the maximum numbers available it doesn’t work.

Even assigning setMaximumFractionDigits, setMaximumIntegerDigits and setMaximumSignificantDigits it doesn’t work like it should, or Am i missing something? please help.

here’s my code…

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

NSNumberFormatter *num = [[NSNumberFormatter alloc] init];

[num setNumberStyle:NSNumberFormatterDecimalStyle];
[num setUsesSignificantDigits:YES];
[num setMaximumFractionDigits:0];
[num setMaximumIntegerDigits:11];
[num setMaximumSignificantDigits:11];

NSString *aString = [textField.text stringByReplacingCharactersInRange:range withString:string]; 
//[NSString stringWithFormat:@"%@%@", textField.text, string];
NSNumber *number = [num numberFromString:aString];

if (number) {
    return YES;
else
    return NO;
}

EDIT:

I reordered the code like Ian said and made the changes that Ink said too and still the same, i can write numbers only but i can write more than 11 numbers.

EDIT 2

Thanks Ian and Ink, now it works, I needed to check that aString.length were minor than 12 and it were a number.

    if (aString.length < 12 && number)
        return YES;
    else
        return NO;

Thanks for any help!

2

There are 2 answers

3
Ian MacDonald On BEST ANSWER

You are assigning number before setting your constraints on num... Try this instead:

[num setUsesSignificantDigits:YES];
[num setMaximumFractionDigits:0];
[num setMaximumIntegerDigits:11];
[num setMaximumSignificantDigits:11];

NSNumber *number = [num numberFromString:aString];

if (number) {
  return [[num stringFromNumber:number] length] <= 11 && [[num stringFromNumber:number] length] == [aString length];
} else {
  return NO;
}
3
InkGolem On

aString should be [textField.text stringByReplacingCharactersInRange:range withString:string]

return aString.length <= 11;

From there you could just check the length of the string, assuming you know that it's a numeric string. If you can't assume that, then do what @Ian MacDonald suggested and reorder your code to look like this:

NSNumber *rawNumber = [num numberFromString:aString];

[num setUsesSignificantDigits:YES];
[num setMaximumFractionDigits:0];
[num setMaximumIntegerDigits:11];
[num setMaximumSignificantDigits:11];

NSNumber *number = [num numberFromString:aString];
return rawNumber == number;

Also notice that just seeing if the number formatter gave you a number isn't good enough. You need to check and see if the number got trimmed by the formatter.