Mahesh Babu
Mahesh Babu

Reputation: 3433

how to validate textfield that allows two digits after

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.

Upvotes: 0

Views: 1008

Answers (3)

Mahesh Babu
Mahesh Babu

Reputation: 3433

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;
}

Upvotes: 1

KingofBliss
KingofBliss

Reputation: 15115

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

Upvotes: 1

Paul Ardeleanu
Paul Ardeleanu

Reputation: 6700

Check the text validity in text field delegate:

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

Upvotes: 0

Related Questions