-2

NOTE: Not to set the Charecter limit, asking for Value of the field limit

In my application I have a uitext field to enter cost of an item.

I can able to restrict the text field to enter only numeric values , that too some specific number of charecters,

But i need to restctrict the textfield to allow only some range of cost only.

i.e i need to restrict cost only 800/- only

if the user tries to type 900 or some thing more than 800 it wont allow to type anymore,

how can we achieve tis any help plese .. thanks

iOS dev
  • 2,254
  • 6
  • 33
  • 56
  • Plz use the search.. has been asked quite a few times – Daij-Djan Sep 30 '14 at 08:57
  • If you like to, you can check out my CKTextField (https://github.com/JaNd3r/CKTextField). It allows you to set simple validation rules (like max string length, max numeric value) via Storyboard. – Christian Sep 30 '14 at 09:06

4 Answers4

2
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField == myTextField) {
        if (string.length == 0) {
            return YES;
        }
        NSString *editedString = [myTextField.text stringByReplacingCharactersInRange:range withString:string];
        NSInteger editedStringValue = editedString.integerValue;
        return editedStringValue <= 800;
    }

    return YES;
}
DeFrenZ
  • 2,172
  • 1
  • 20
  • 19
1

first set your textfield delegate...

yourTextField.delegate=self

then,

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
        NSString *str=[NSString stringWithFormat:@"%@%@",textField.text,string];
        if ([str integerValue]>800) {
            return NO;
        }
        else{
            return YES;
        }
    }

if You have more than one textfield then you need to assign tag value and put another condition to identify textfield and if you have only one text field use same code.

user2493047
  • 119
  • 8
0
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
    if([string isEqualToString:@""]) {
        return YES;
    }
     NSString *stringToValidate= [textField.text stringByReplacingCharactersInRange:range withString:string]];
        if([stringToValidate doubleValue]>800){
return NO;
}
return YES;
}

Check the above code and it can help you

Ramesh Muthe
  • 811
  • 7
  • 15
-1

try this

handle the "Editing Changed" event

[textField addTarget:self 
               action:@selector(editingChanged:)
     forControlEvents:UIControlEventEditingChanged];

and the selector:

    -(void) editingChanged:(id)sender {
       // your code

}
mond
  • 38
  • 6
  • In this way you can only do things **after** the editing happened. He wanted to stop the user to enter invalid values. – DeFrenZ Sep 30 '14 at 09:25