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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…