views:

85

answers:

2

If I have a UITextField which the user is inputing a registration number, which has the format: 11-11-1111

(that is 2 digits, a dash, 2 digits, a dash, four digits)

How do I force the user to enter this kind of data only (as they are actually entering it)... so they can't enter anything except 0-9 in the first character, and only '-' for the third character etc.

A: 

You can check the input with a regex and show an error message, if it's in the wrong format. See here. Or you can split the string at the dashes and look at the parts (convert them to integer, for example) (see here).

Another (untested and theoretical) approach would be: set the textfield delegate to your controller:

myTextField.delegate = self

and then try:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSCharacterSet *nonNumberSet = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789."] invertedSet];
return ([string stringByTrimmingCharactersInSet:nonNumberSet].length > 0);
}
Juri Keller
I would rather not show an error. I want to actually limit what they can enter, as they are entering it.
cannyboy
+1  A: 

From a UX point of view, since the '-' characters are fixed, limit the input to just 0-9 by setting the keyboardType property of UITextField to UIKeyboardTypeNumberPad.

Implement UITextFieldDelegate protocol's textField:shouldChangeCharactersInRange:replacementString: method and check the length of the textField.text and append the '-' character automatically when the length is 2 or 5. When the length reaches 10 characters, do not accept any new characters, just deletes.

falconcreek