Reputation: 1493
I'm writing application in which I need to validate text entered by user to UITextField
, char by char with some method.
The difficult thing is that client wants to do all the validation before user see character in the UITextField because there might be situation that his server application doesn't support '$'
sign, so in my validation method I should replace it with 'USD'
string - and he doesn't want user to see '$'
, just 'USD'
immediately.
I know about events like UIControlEventEditingChanged
etc., but still, I don't know 2 things:
how to access character typed by user before it's seen in UITextField
and execute validation there
how to subtitute this character 'on the fly' and put it manually to UITextField (but I suppose I'll just append this to [[textField] text]
NSString
Thank You in advance for any help :)
Upvotes: 0
Views: 317
Reputation: 14834
Similar to omz's answer but more complete code if you need:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *filtered;
filtered = [string stringByReplacingOccurrencesOfString:@"$" withString:@"USD"];
//optionally if you want to only have alphanumeric characters
//NSMutableCharacterSet *mcs1 = [[[NSCharacterSet letterCharacterSet] invertedSet] mutableCopy]; //only alphabet character
//[mcs1 removeCharactersInString:@"0123456789"];
//filtered = [[filtered componentsSeparatedByCharactersInSet:mcs1] componentsJoinedByString:@""];
//release mcs1;
return [string isEqualToString:filtered];
}
Upvotes: 0
Reputation: 53551
Implement the UITextFieldDelegate
method textField:shouldChangeCharactersInRange:replacementString:
, e.g.:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
BOOL validated = ...; //do your validation
return validated;
}
Upvotes: 1