0

I'm trying to figure out a way to 'force' the UITextField to follow a set method. For example:

I have successfully limited it to only accept 4 characters as a max but I need it to set the 4 character limit to be first character "Numeric" second character "AlphaNumeric" Third / Fourth to be "Numeric" for example : 1Z11

I also can't figure out if you can force capitalised lettering or not like you can via ASCII or VBA.

Any help would be perfect, I have looked around but all I can only find is how to force one or the other (all numeric or all alphanumeric).

Kindest Regards Jamie

-Edit one-

I have no code for the limiting of the characters as I said above I can only find ways to limit one or the other so I have no code inputted yet (Can link to the stack posts if you want?).

JamieB
  • 247
  • 4
  • 8
  • 17
  • how about editing your question to show how you are currently limiting it to only accepting certain characters? i.e. show code. – Michael Dautermann May 20 '14 at 15:27
  • For the capitalised lettering : http://stackoverflow.com/questions/2027164/iphone-force-textbox-input-to-upper-case – Guntis Treulands May 20 '14 at 15:28
  • Thank you @GuntisTreulands for this, this looks like it will work perfectly. – JamieB May 20 '14 at 15:52
  • @MichaelDautermann I have no code for the limiting of the characters as I said above I can only find ways to limit one or the other so I have no code inputted yet (Can link to the stack posts if you want?). – JamieB May 20 '14 at 15:52

2 Answers2

1

Try implementing something like this for the delegate method :

 - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (range.location != 1) {
        NSScanner *scanner = [NSScanner scannerWithString:string];
        BOOL isNumeric = [scanner scanInteger:NULL] && [scanner isAtEnd];
        return isNumeric;
    }else if (range.location<4){
        return YES;
    }
    return NO;
 }
streem
  • 9,044
  • 5
  • 30
  • 41
0

Please try the below

NSCharacterSet *numeric = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
NSCharacterSet *alphaNumberSet = [[NSCharacterSet alphanumericCharacterSet] invertedSet];


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

     //allow backspace
       if ([characters isEqualToString:@""])
{
    return YES;
}
       switch (field.text.length) {
            case 0:
            case 2:
            case 3:
        {
             BOOL retVal =  ([characters rangeOfCharacterFromSet:numeric].location == NSNotFound);
            return retVal;
        }
            break;
         case 1:
        {
            BOOL retVal =  ([characters rangeOfCharacterFromSet:alphaNumberSet].location == NSNotFound);
            return retVal;

        }
        default:
            return NO;
            break;
    }

}
Bobj-C
  • 5,276
  • 9
  • 47
  • 83