Question

Maybe it's a simple question but I can't figure out the right way to do it.

I have a UITextField. Since I need to validate the text that is inserted within this text field, I'm currently using the UITextFieldDelegate method - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string like the following:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
   // do validation here
   // return YES or NO depending on previous validation
}

Since I have some text fields (they not belong to the same controller where the validation is performed) and I don't want to duplicate text fields validation code, how can I achieve an elegant way to centralize a similar validation? I don't know if subclassing is the right way, but in this case I need to use the same delegation method (the one listed above) in different parts of the same app.

Thank you in advance.

Was it helpful?

Solution

This depends on how much information your validation code requires. If the arguments of textField:shouldChangeCharactersInRange:replacementString: are all you need to determine whether to return YES or NO, then you can just use the same delegate for all your textFields.

If you need to track and store information about previous validations in order to make validation decisions, the easiest way would be to package all that state up into an object, and have an array of those objects, each corresponding to a specific UITextField. Then, in textField:shouldChangeCharactersInRange:replacementString: you would use the state corresponding to the textField that was passed in.

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