简体   繁体   中英

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

To build the full string you must take into account edits in the middle of the text field too. Made some changes to the code posted above.

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    BOOL result = NO;

    // Build the final string...   
    NSMutableString *fullString = [[NSMutableString alloc] init];
    NSUInteger firstChunkLength = range.location;
    NSUInteger secondChunkStart = range.location + range.length;
    NSUInteger secondChunkLength = [textField.text length] - secondChunkStart;

    [fullString appendString:[textField.text substringWithRange:NSMakeRange( 0, firstChunkLength )]];
    [fullString appendString:string];
    [fullString appendString:[textField.text substringWithRange:NSMakeRange( secondChunkStart, secondChunkLength )]];

    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    NSNumber *replaceNumber = [formatter numberFromString:fullString];
    NSNumber *originalNumber = [formatter numberFromString:textField.text];

    result = ( replaceNumber != nil && replaceNumber != originalNumber );

    [fullString release];
    [formatter release];

    return result;
}

This method is used to validate a UItextfield for only numeric values.

It is a perfect integer validation.

- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSCharacterSet *nonNumberSet = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789."] invertedSet];
    return ([string stringByTrimmingCharactersInSet:nonNumberSet].length > 0);
}

Thankfully, now that we have Swift, this is MUCH easier. You do have to construct the prospective string (hopefully when Apple rewrites Cocoa in Swift this interface will add that).

Meantime, here is a simple one liner to do so:

let constructedString = (self.inputField.text! as NSString).stringByReplacingCharactersInRange(range, withString: string)

Note, self.inputField is of course an outlet to the field in question. Also, the casting to NSString is because the range we are passed is an NSRange.

I have create a class JSInputField (subclass of UItextField) which lets user add validation very easily. For eg.

JSInputField *inputField = [[JSInputField alloc] initWithFrame:CGRectMake(10, 100, 300, 50)];
[self.view addSubview:inputField];
[inputField setPlaceholder:@"Enter Text"];
[inputField setRoundedCorners:UIRectCornerAllCorners];
[inputField addValidationRule:JSCreateRuleNotNullValue]; //This will validate field for null value. It will show error if field is empty.
[inputField addValidationRule:JSCreateRuleNumeric(2)];  //This will validate field for numeric values and restrict to enter value upto 2 decimal places.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM