MaheshBabu MaheshBabu - 8 months ago 90
Objective-C Question

UITextField validation

I am creating a text field.

Whenever the value in text field is greater than 100 I need to display an alert saying "value must be less than 100", then the text field's value should be cleared.

How can I do this?


You can have your view controller conform to the UITextFieldDelegate protocol and implement the -textField:shouldChangeCharactersInRange:replacementString: method:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (range.location == 0 && string.length == 0) {
        return YES;

    // Build up the resulting string…
    NSMutableString *fullString = [[NSMutableString alloc] init];

    [fullString appendString:[textField.text substringWithRange:NSMakeRange(0, range.location)]];
    [fullString appendString:string];

    // Set up number formatter…
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    NSNumber *replaceNumber = [formatter numberFromString:fullString];

    [fullString release];
    [formatter release];

    return !(replaceNumber == nil || [replaceNumber intValue] > 100);