depicus

changing the digital world one bit at a time...

Blants (noun) the rants of a blogger

Because you can never trust a user…

November 4, 2010 by The Man

You will be surprised, or not, at the stuff people will try and type into UITextField boxes. Here is some code that uses shouldChangeCharactersInRange to a) check the characters entered and b) restrict the length and as a bonus add charachters that the user has to type.

The field requires the user to input a mac address which is a alpha numeric field but letters are only valid up to F.

As always this code is cobbled from other pioneers in the interweb, thanks to them.

- (BOOL) textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString*)textEntered 
{
    if (textField.tag == 101)
    {
        NSCharacterSet *myMacAddress = [NSCharacterSet characterSetWithCharactersInString:@"0123456789abcdefABCDEF-:"];
    for (int i = 0; i < [textEntered length]; i++) 
    {
        unichar c = [textEntered characterAtIndex:i];
        if (![myMacAddress characterIsMember:c]) 
        {
            return NO;
        }
        if (([textField.text length] == 1) || ([textField.text length] == 4) || ([textField.text length] == 7) || ([textField.text length] == 10) || ([textField.text length] == 13))
        {
           [textField setText:[NSString stringWithFormat:@"%@%@-",[textField text],textEntered]]; 
            return NO;
        }
        int limit = 16;
        return !([textField.text length]>limit && [textEntered length] > range.length);
    } 
    }
    return YES;
}

Not perfect but better than nothing.