UITextField append / between dates while enforcing character limit

39 views Asked by At

I am using a UITextField and needing to enforce the following date format:

12/17

enter image description here

I know how to enforce the 4 character limit:

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

    if ([textField isEqual:self.billingExpirationDate]) {

        if (range.length + range.location > textField.text.length) {
            return NO;
        }

        NSUInteger newLength = [textField.text length] + [string length] - range.length;

        return newLength <= 4;

    }

    return YES;

}

However, if I try to insert the / into the string after two numbers have been typed, it screws things up and won't let the user use the delete button.

Does anyone have any ideas how I could follow the needed format, while only allowing users to enter four numeric characters, and obviously letting them delete them if needed?

2

There are 2 answers

0
VD Patel On BEST ANSWER

You can use this for Delete characters.

if(string.length==0 && range.length==1)
   {
       return YES;
   }

Let me know if you need for more Help. Thanks.....

0
Ishaan Sejwal On

So I ran your code and implemented a scanner to check if string is integer and if range reaches location+length of 2 while inputting and not deleting, a '/' prepended before string

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

    if ([textField isEqual:self.billingExpirationDate]) {

    NSScanner *scanner = [NSScanner scannerWithString:string];
    BOOL isInteger=[scanner scanInteger:NULL] && [scanner isAtEnd];
    if (string.length==0) isInteger=YES; //since an empty string while deleting will also return NO
    if (isInteger)
    {
       if (range.length + range.location > textField.text.length) {
        return NO;
       }

       if (range.length + range.location==2 && string.length) {
           [textField setText:[textField.text stringByAppendingString:@"/"]];
       }


    NSUInteger newLength = [textField.text length] + [string length] - range.length;

    return newLength <= 5;
    }
    else return NO;

    }

    return YES;

}