Search code examples
iosinputblockrestrict

ios restrict to input more than one "." or "," (if it is russian localization)


problem is that on russian localization numeric pad has "," instead of "." and when view is loaded i have "0.0" in the text field, when I thought that user would be able to input only "." I used such code to prevent inputting more than one "."

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];

    NSArray  *arrayOfString = [newString componentsSeparatedByString:@"."];

    if ([arrayOfString count] > 2 )
    {
        return NO;
    }
}

but when occured that in rus localization pad appears with "," instead of "." I can't find out how I can prevent of inputting "," if there is "." already

and i am replacing inputted "," with "." so i will be glad if someone helps to restrict inputting "," if thereis "." in the text field already


Solution

  • You can use NSNumberFormatter to have a localized number in your field when it displays.

    NSNumberFormatter * formatter =  [[NSNumberFormatter alloc] init];
    [formatter setNumberStyle:kCFNumberFormatterDecimalStyle];
    [formatter setMaximumFractionDigits:1];
    [formatter setLocale:[NSLocale currentLocale]];
    NSString * myString = [formatter stringFromNumber:[NSNumber numberWithFloat:123.456]];
    

    from https://stackoverflow.com/a/11504127/719866

    You can use the formatter in your check to see if the value entered by the user is valid for that locale with the -numberFromString: method.