Ahad Porkar
Ahad Porkar

Reputation: 1698

Adding different type of validation on multiple UITextField in uitableview

Im using multiple uitextfield in my uitableview row.

for example user can type the range of number in two of these uitextfield.

now how can i handle some validation on entered value in these uitextfield ?

for example uitextfield1 shouldnt be lower 1 and uitextfield2 shouldnt be highter than 100.

this is my old code to set the textfield have only numerical value :

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

        NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ACCEPTABLE_CHARECTERS] invertedSet];

        NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];

        return [string isEqualToString:filtered];

    return YES;
}

and in my cellForRowAtIndexPath :

static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
UITextField * UTX1 = (UITextField *)[cell viewWithTag:1];
UITextField * UTX2 = (UITextField *)[cell viewWithTag:2];
UTX1.delegate = self;
UTX2.delegate = self;

Upvotes: 0

Views: 385

Answers (2)

Yuvrajsinh
Yuvrajsinh

Reputation: 4584

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string  {
      // allow backspace
      if (!string.length)
      {
           return YES;
      }

      // allow digit 0 to 9
      if ([string intValue])
      {
            if(textfield.tag==1){ // First textfield
                 if([string intValue]<1){
                        return NO;
                 }
            }
            else if(textfield.tag==2){ // Second textfield
                 if([string intValue]>100){
                        return NO;
                 }
            }
            return YES;
      }
      return NO;
}

You can change conditions for range of value to allow for each textfield as per your need.

Upvotes: 1

chaithraVeeresh
chaithraVeeresh

Reputation: 258

Validate the textfield based on tag.

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

        NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ACCEPTABLE_CHARECTERS] invertedSet];

        NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];

if(textField.tag == 1)
{
return [string isEqualToString:filtered] && [string intValue]> 1 ;
}
if(textfield.tag == 2)
{
return [string isEqualToString:filtered] && [string intValue] < 100;
}
   return YES;
}

Upvotes: 1

Related Questions