how to do UItextfield should allow only value between Range

285 views Asked by At

My Problem is i have to do Like User can enter values in Range ... My range is coming from json

here's my code whatever i tried ... here a,b is my start range and b is end range user can enter values better this range not out of range

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
  if (textField)
  {
    NSData *data = [((MDCFlowDetails *)_flow).flow_data dataUsingEncoding:NSUTF8StringEncoding];
    id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    NSString *a = [json objectForKey:@"startrange"];
    NSString *b = [json objectForKey:@"endrange"];
    NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];

    NSString *expression = @"^([0-9]+)?(\\.([0-9]{1,2})?)?$";

    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:expression
                                                                           options:NSRegularExpressionCaseInsensitive
                                                                             error:nil];
    NSUInteger numberOfMatches = [regex numberOfMatchesInString:newString
                                                        options:0
                                                          range:NSMakeRange(0, [newString length])];
    if (numberOfMatches == 0)
        return NO;
}

return YES;
}
1

There are 1 answers

8
Mehul Patel On BEST ANSWER

I think it can be done simply by just checking length of textfield.

Put a condition on low and high end of range when user enter text in textfield.

See below code:

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

        NSData *data = [((MDCFlowDetails *)_flow).flow_data dataUsingEncoding:NSUTF8StringEncoding];
        id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        NSInteger a = [[json objectForKey:@"startrange"] integerValue];
        NSInteger b = [[json objectForKey:@"endrange"] integerValue];

        if (newString.length > a && newString.length > b) {
            // Check both range are satisfied.
            return NO;
        }

    }
    return YES;
}