user1673099
user1673099

Reputation: 3289

Textfield Input Validation in iPhone SDK

I have to put validation on a UITextField for user input.

The user must input into the textfield a value

i.e. 70-80 or 85 mean num-num or num

Right now, I just allow to user to input only digits& - but drawback is that user can also input - number of times.

// My code is as follow

NSCharacterSet * set = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789-"] invertedSet];

    if (([txtMarks.text rangeOfCharacterFromSet:set].location != NSNotFound )||[txtMarks.text isEqualToString:@""] ) {

        UIAlertView *alt=[[UIAlertView alloc]initWithTitle:@"Error" message:@"Invalid Input" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
        [alt show];
        [alt release];
    }

Upvotes: 3

Views: 3642

Answers (3)

Girish
Girish

Reputation: 4712

Try it using the following regular expression, It restricts user to enter more than one -.

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

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

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

Upvotes: 1

Aman Aggarwal
Aman Aggarwal

Reputation: 3754

Try this first find whether your string contains -

Here subtring is -

if ([txtMarks.text hasPrefix:@"-"]||[txtMarks.text hasSuffix:@"-"])
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"sorry " message:@"invalid inoput as it has - at start or end" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
    [alert show];
    [alert release];
}
else
{
  NSRange textRange;
  textRange =[string rangeOfString:substring];

  if(textRange.location == NSNotFound)
  {
      //Does not  contain the substring
     NSlog(@" string contains only num")

  }
  else
  {
     int times = [[txtMarks.text componentsSeparatedByString:@"-"] count];
     if(times==2)
     {
         Nslog(@"num-num input")

     }
     else
    {
       UIAlertView *alt=[[UIAlertView alloc]initWithTitle:@"Error" message:@"'-' used more than one" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
         [alt show];
         [alt release];    
    }
  }  
}

Upvotes: 1

βhargavḯ
βhargavḯ

Reputation: 9836

Simply Try this,

    int times = [[txtMarks.text componentsSeparatedByString:@"-"] count]-1;
    if(times>1)
    {
        UIAlertView *alt=[[UIAlertView alloc]initWithTitle:@"Error" message:@"'-' used more than one" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
        [alt show];
        [alt release];    
    }

EDIT 1

Using NSPredicate we can do it. Try this,

    NSString *regex = @"[0-9]+(-[0-9]+)?";
    NSPredicate *testRegex = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];

    if([testRegex evaluateWithObject:textField.text])
        NSLog(@"Match");
    else
        NSLog(@"Do not match");

Hope that can help.

Upvotes: 4

Related Questions