views:

221

answers:

2

i want to let the user type in the name of a new file, so there are certain characters i want to prevent entry on. is there a special keyboard i can use or can i disable certain keys on the iphones keyboard.

is the answer to just run a regular expression on the input text and tell the user the filename is invalid (if so what would that regular expression be?)

ANSWER: (or what i ended up doing)

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

    BOOL valid;
    //if the user has put in a space at the beginning
    if ([string isEqualToString:@" "]){
     if (range.location == 0){
      valid = NO;
     }
     else{
      valid = YES;
     }
    }
    //otherwise test for alpha numeric
    else{
     NSCharacterSet *alphaSet = [NSCharacterSet alphanumericCharacterSet];
     valid = [[string stringByTrimmingCharactersInSet:alphaSet] isEqualToString:@""];
    }

    //print the warning label
    if (valid == NO){
     [errorLabel setText:@"Invalid input"];
    }
    else{
     [errorLabel setText:nil];
    }
    return valid;
}
A: 

You can implement the UITextFieldDelegate protocol and use textField:shouldChangeCharactersInRange:replacementString: to watch the text entry and prevent unwanted characters by returning NO.

gerry3
+1  A: 

You can implement the delegate method

For UITextField,

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;   // return NO to not change text

For UITextview

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text;

and decide weather to append the entered characters or not.

Prakash
this will work, but do you know of any way to disable the keys you dont want entry on?
Aran Mulholland
If you mean, hiding the unwanted keys from the keyboard itself, you have to implement your own keyboard!
Prakash