Question


I've got an UITextField and I need to allow only numbers, comma or point typing in this field.
How can I check if this string contains any character instead of these above and how can I replace/delete them?

My field will store a cost and I need only numbers, comma or point...

Can anyone help me?
Thanks!

Was it helpful?

Solution

You can use the -textFieldDidEndEditing: method from the UITextFieldDelegate protocol. This method is called whenever a text field resigns the first responder status (i.e. ends editing). This is the chance to check the entered String. If you want to perform a check after each character that has been input, use -textField:shouldChangeCharactersInRange:replacementString: as donkim suggests.

OTHER TIPS

For the textfield, you could use the UITextFieldDelegate and implement the textField:shouldChangeCharactersInRange:replacementString: method. According to the docs, "the text field calls this method whenever the user types a new character in the text field or deletes an existing character." In the method, you should do a check for all non-number characters and remove them.

Instead to check the string why cant you assign the keyboard value of the textfield as NumberPad. So that the user will not be able to type a string.

You can do it by monitoring user input in the field and automatically removing non-matching characters. Create an IBAction method:

- (IBAction)validateEntry:(id)sender;

then attach it to the text field's Editing Changed event. The method will be called every time the text in the field changes, whether from the user typing or from the user pasting text in.

Inside the method you can examine the text and remove offending characters or, more politely, update a UILabel that tells the user they've entered invalid characters and disable any submit buttons until it's fixed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top