BartoNaz
BartoNaz

Reputation: 2893

Validate text in TextField

I have in my program a textfield which represents a fileName from a model object using bindings. I want that this textField could be used to enter a new fileName and after user presses Enter it should send the message to my model object that value of fileName has changed in my textField, then inside my model object the method for checking if such filename can be used is called. And if it returns true, then it should apply new value to my model object, if not, then value in my textField should undo to initial value.

Does somebody know how it could be implemented? I can validate my value but I can't make my textField refresh to initial value. As for both changing the model object value, and texField refreshing should be used single method which is KVC compliant I don't know how to implement such behaviour.

Any help would be very appreciated.

Upvotes: 0

Views: 1239

Answers (1)

jscs
jscs

Reputation: 64002

This doesn't sound like a good UX to me; as a user, I would be upset to find that if I made a simple typo in a text field, it completely erased what I had just input. It would be much better to show a message indicating what was wrong and how the user can fix it. Nonetheless...

I think you should set up a text field delegate. Have the delegate keep a variable holding the last valid string that was input. Then in textFieldShouldEndEditing:, do your check for validity, and if the check does not pass, set the text field's value to that variable and return NO. If it does pass, change the variable to hold the new valid string and return YES.

Upvotes: 1

Related Questions