I find all kinds of phone number validations on stackoverflow for the iphone but none seem to validate they just seem to change the format. example Phone number formatting.
EDIT: I read the question again and saw that you wanted to validate, not highlight the phone number, so I moved up the section on NSDataDetector
.
You can use NSDataDetector
(which is a specialized subclass of NSRegularExpression
) to search for phone numbers in an NSString
(this uses the iPhone's default phone number detection algorithm, I believe).
NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypePhoneNumber
error:&error];
NSUInteger numberOfMatches = [detector numberOfMatchesInString:string
options:0
range:NSMakeRange(0, [string length])];
If you use a UITextView
(but probably not UITextField
like you are using here), you can highlight a phone number using the iPhone's default phone number detection algorithm by setting its dataDetectorTypes
property:
textView.dataDetectorTypes = UIDataDetectorTypePhoneNumber;
See UIDataDetectorTypes
for other kinds of data detectors.
First, real phone number validation is pretty complicated. Are you limiting yourself to NANP (North America Numbering Plan), or are you looking for E.164 numbers? It looks like you're trying to mostly match E.164, though this isn't usually the kind of number that most people would enter.
Your match requires a plus, followed by a sequence of digits between seven and fifteen long with optional spaces between them. Is this what you mean? What strings are you passing in?
Note that as of iOS4, there is NSRegularExpression
that is a bit better for this than NSPredicate
.
Using this validation you can only enter 10 numbers. You can change it's length according to your requirement.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
BOOL valid = [[NSPredicate predicateWithFormat:@"SELF MATCHES %@", REGEX_FOR_INTEGERS] evaluateWithObject:_textFieldValidate.text];
if(valid){
if(range.length + range.location > textField.text.length)
{
return NO;
}
NSUInteger newLength = [textField.text length] + [string length] - range.length;
return newLength <= 10;
}
return YES;
}
Hope this will help you.