I am presenting the user with a field that displays the number keyboard and only want them to be able to enter numbers with decimal it should be only one. After decimal it is should be at least 2 digits will be there. There should b开发者_如何学编程e at least one digit before the decimal. Then the input can`t be 0 or 0.00. Suppose if user enter the number 123456 it is accepted then 123.56 it also accepted how can I do this one please help me.
you can make a regex for this requirement like:-
NSString *numberRegEx = @"[0-9]+[.]{0,1}+[0-9]{0,2}";
NSPredicate *numberTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", numberRegEx];
//Valid email address
if ([numberTest evaluateWithObject:textField.text] == YES)
{
NSLog(@"correct value");
}
else
{
NSLog(@"incorrect value");
}
First, add a target for UIControlEventEditingChanged of your text field:
[textField addTarget:self action:@selector(onEdit:) forControlEvents:UIControlEventEditingChanged];
add a BOOL property to your class:
@property(nonatomic, assign) BOOL formatting;
then create an onEdit: method like this:
-(void)onEdit:(UITextField*)field {
//if you have more than one text field you can check for the one you need to format
if(!self.formatting) {
NSString* formattedText = ...//get the formatted text according to your rules
self.formatting = YES;//infinite loop prevention
field.text = formattedText;
self.formatting = NO;
}
}
You can impose all your conditions in the -(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
method. Here, textField.text
will be the most recent text that the user has entered. You can parse it and see whether any of your conditions are not being met. Return NO in that case.
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if(allConditionsMet)
return YES;
return NO;
}
HTH,
Akshay
精彩评论