Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
523 views
in Technique[技术] by (71.8m points)

objective c - IPhone simple phone number validation

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.

Goals: this number is being entered via an alert. North American with or with out dashes.

so have some code but every thing is coming up as invalid any ideas.

- (void)textFieldDidEndEditing:(UITextField *)textField {

NSString *str=@"^\+(?:[0-9] ?){6,14}[0-9]$";
NSPredicate *no=[NSPredicate predicateWithFormat:@"SELF MATCHES %@",str];
if([no evaluateWithObject:textField.text]==NO)
   { 

       UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Warning" message:@"Please Enter correct contact no." delegate:self cancelButtonTitle:@"ok" otherButtonTitles:nil];

       [alert show];
       [alert release];

   }
   else{
NSString *textValue = textField.text;
NSLog(@"Value: %@", textValue);
   }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...