0

i have to validate text field that allows only two digits after .

eg:12.34

if user enter more then two digits it won't allows text.

let me know is it understandable or no

how can i done,can any one please help me.

Thank u in advance.

Mahesh Babu
  • 3,395
  • 9
  • 48
  • 97

3 Answers3

1

You should code in the following delegate method,

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
 NSArray *sep = [string componentsSeparatedByString:@"."];
 if([sep count]==2)
 {
  NSString *sepStr=[NSString stringWithFormat:@"%@",[sep objectAtIndex:1]];
  if([sepStr length] >2)
  //do whatever you want
 }
}

You can also check if they use many decimal points by,

if([sep count]>2)
 //use only one decimal point
KingofBliss
  • 15,055
  • 6
  • 50
  • 72
  • NSArray *sep = [string componentsSeparatedByString:@"."]; if([sep count]==2) { NSString *sepStr=[NSString stringWithFormat:@"%@",[sep objectAtIndex:1]]; if([sepStr length] >2) { NSLog(@"textfield validating %@",sepStr); //do whatever you want } } i try this but does n't print any thing – Mahesh Babu Feb 09 '11 at 04:00
  • The if statement will be executed only after the decimal point is encountered – KingofBliss Feb 09 '11 at 04:26
  • Check whether you set your delegate – KingofBliss Feb 09 '11 at 04:27
  • if i try this NSArray *sep = [string componentsSeparatedByString:@"."]; if([sep count]==2) { NSString *sepStr=[NSString stringWithFormat:@"%@",[sep objectAtIndex:1]]; NSLog(@"hello"); } Then it prints when i place . in textfield,but nothing will happen when i place ur above code – Mahesh Babu Feb 09 '11 at 12:31
  • Of course it will check for . symbol then it will check if there is more than 2 digits after . symbol – KingofBliss Feb 09 '11 at 16:20
1

I resolve my problem by using this code.

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

    NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];

    NSArray *sep = [newString componentsSeparatedByString:@"."];
    if([sep count]>=2)
    {
        NSString *sepStr=[NSString stringWithFormat:@"%@",[sep objectAtIndex:1]];
        return !([sepStr length]>2);
    }
    return YES;
}
Mahesh Babu
  • 3,395
  • 9
  • 48
  • 97
0

Check the text validity in text field delegate:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
Paul Ardeleanu
  • 6,620
  • 2
  • 40
  • 41