Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to validate textfield that allows only single decimal point in textfield?

I need to restrict user to enter only two digit after decimal point. I have achieved this by following code in textfield delegate shouldChangeCharactersInRange. But its allowing to enter more than one dot. how to restrict this? Thanks in advance.

            NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
            NSArray *sep = [newString componentsSeparatedByString:@"."];
            if([sep count]>=2)
            {
                NSString *sepStr=[NSString stringWithFormat:@"%@",[sep objectAtIndex:1]];
                NSLog(@"sepStr:%@",sepStr);

                return !([sepStr length]>2);
            }
            return YES;
like image 462
Gowtham Avatar asked Dec 01 '22 21:12

Gowtham


1 Answers

The best way is to use Regular Expression in shouldChangeCharactersInRange: delegate method like this

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

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

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

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

After implementing this valid strings are:
12.004546
4546.5456465
.5464
0.454

So on....

You can also restrict number of integer after decimal by using this Regular Expression

@"^([0-9]*)(\\.([0-9]{0,2})?)?$"

After implementing this valid strings are:
12.00
4546.54
.54
0.45

like image 122
Nilesh_iOSDev Avatar answered Dec 21 '22 05:12

Nilesh_iOSDev