Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...