Reputation: 5834
I am developing an iOS application in which I have to Validate user's Phone number when he is typing.
Here is the conditions:
1. Starting number can only be 9,8,7
2. Length = 10
3. Only Numbers
If users enters any other character then nothing should be printed on textfield.
I am writing all my code in - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
method.
I have successfully implemented these three conditions. I am stuck in this fourth condition:
**4. User enters 9834 then he jumps to first position and then types 19834**
I am not able to handle this. How can I know the users has typed some numbers and now he is typing on first position. So that I can return false.
Upvotes: 0
Views: 404
Reputation: 7552
The best way to do this is with libPhoneNumber. If the link is broken, just google for it. It's a library from Google, originally written for Android. It's been ported to several languages, including Objective-C.
Anything you come up with will be missing corner cases and all sorts of rules that libPhoneNumber handles for you. This is one area where "don't roll your own" is the way to go.
Upvotes: 0
Reputation: 5435
you can use range
to find the location where user is editing.
use range.location
or range.length
to validate.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
if(range.location==0){
if ([string isEqualToString:@"9"] || [string isEqualToString:@"8"] || [string isEqualToString:@"7"]) {
return YES;
}
else{
return NO;
}
}
else{
return YES;
}
}
Upvotes: 2