Reputation: 1643
Hi I need phone number validation for France.
Valid format : +262#########
Validation done in textDidChang: so every I need to check every number belong to above number.
My Regex below
[[NSPredicate predicateWithFormat:@"SELF MATCHES %@", @"+2?6?2?\d?\d?\d?\d?\d?\d?\d?\d?\d?"] evaluateWithObject:@"+262989878989"]
While execute this line app crash
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Can't do regex matching, reason: (Can't open pattern U_REGEX_RULE_SYNTAX (string 2, pattern +2?6?2?\d?\d?\d?\d?\d?\d?\d?\d?\d?, case 0, canon 0))'
Help me to fix this.
Upvotes: 3
Views: 6197
Reputation: 1643
[[NSPredicate predicateWithFormat:@"SELF MATCHES %@", @"\\+2?6?2?\\d?\\d?\\d?\\d?\\d?\\d?\\d?\\d?\\d?"] evaluateWithObject:phoneNumber];
phoneNumber will be +2, +26, +262, ....... +262#########..
Before +
I need to put \\
. That is my mistake.
Upvotes: 1
Reputation: 438467
The \d
is not working because it's in a string literal, and you have to escape the \
(e.g. @"\\d"
). You should also escape the +
because that has a special meaning in regex, too (e.g. @"^\\+262\\d{9}$"
).
Note the ^
and $
which match the start and end of the string, if that's what you meant. Or if you're looking for this anywhere in the larger string, you should check for word boundaries. Without one of these two approaches, you'll get false positive with +262
followed more than nine characters.
--
If you're trying to make sure someone enters a number that matches this format, you can do something like:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *result = [textField.text stringByReplacingCharactersInRange:range withString:string];
return [[NSPredicate predicateWithFormat:@"SELF MATCHES %@", @"^(\\+(2(6(2\\d{0,9})?)?)?)?$"] evaluateWithObject:result];
}
That will match any string that is the beginning of a valid phone number.
Upvotes: 3
Reputation: 4917
NSString *phoneNumber = ...;
NSString *phoneRegex = @"^((\\+)|(00))[0-9]{6,14}$";
NSPredicate *test = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneRegex];
BOOL matches = [test evaluateWithObject:phoneNumber];
Upvotes: 0