Search code examples
iosuitextfielduitextfielddelegate

UITextField accepting only one decimal point with max 3 digits before decimal point & max 2 digits after decimal point


I want to restrict UITextField to accept only one decimal point.

Also maximum 3 digits are allowed before decimal point & maximum 2 digits allowed after decimal point.

Please note that minimum digits can be 1 and decimal cant be entered a first.

How can I achieve it?


Solution

  • Thank you so much all folks for helping. By referring those answers I framed below answer.

    EDIT

    While textfields having e.g. 462. & user touches backspace results to 462 which ideally should result to 46

        - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
        {
            NSString *strTextField = [textField.text stringByReplacingCharactersInRange:range withString:string];
        // restrict textfield from entering ./0 at first place
        if (strTextField.length > 0) {
            NSString *theCharacterAtIndex0 = [NSString stringWithFormat:@"%c", [strTextField characterAtIndex:0]];
            if ([theCharacterAtIndex0 isEqualToString:@"."] || [theCharacterAtIndex0 isEqualToString:@"0"]) {
                return NO;
            }
        }
        //    NSLog(@"%@ , %@", textField.text, strTextField);
    
        // automatically add decimal point after 3 digits entered
        if (![textField.text containsString:@"."]) {
            if (strTextField.length == MAX_LENGTH_BeforeDecimal && ![strTextField containsString:@"."]) {
                strTextField = [strTextField stringByAppendingString:@"."];
                textField.text = strTextField;
                return NO;
            }
        }
    
        // when decimal is deleted
        if ([textField.text containsString:@"."]) {
            if (![strTextField containsString:@"."]) {
                int indeOfdecimal = (int)[textField.text rangeOfString:@"."].location;
                NSString *strBeforeDecimal = [textField.text substringToIndex:indeOfdecimal];
                textField.text = strBeforeDecimal;
            }
        }
    
        NSArray *separator = [strTextField componentsSeparatedByString:@"."];
        // to restrict textfield to single decimal
        if([separator count] > 2 ) {
            return NO;
        }
        if([separator count] >= 2) {
            // restrict the max digits before & after decimal points
            NSString *sepStr0 = [NSString stringWithFormat:@"%@",[separator objectAtIndex:0]];
            NSString *sepStr1 = [NSString stringWithFormat:@"%@",[separator objectAtIndex:1]];
            if ([sepStr0 length] > 3) {
                return NO;
            }
            if ([sepStr1 length] > 2) {
                return NO;
            }
        }
        return YES;
    }