2

I have to validate phone no from following regEx.

//**regExpPattern** : "+?[0-9]{0,3}( |-)?[0-9]{4}( |-)?[0-9]{3}( |-)?[0-9]{3}"
-(BOOL) textFieldValidation:(NSString *)checkString withRegEx:(NSString*)regExpPattern
{
      NSString *stringToValidate = [[NSString alloc]initWithString:checkString];
      NSString *pattern = [[NSString alloc]initWithString:regExpPattern]
      NSLog(@"%@ %@",checkString,regExpPattern);


      NSPredicate *myTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",pattern];

            if ([myTest evaluateWithObject:stringToValidate]){
                return YES;
            }
            return FALSE;
        }

I'm getting the following exception :

'NSInvalidArgumentException' 'Can't do regex matching, reason: (Can't open pattern U_REGEX_RULE_SYNTAX (string 6789054321, pattern +[?][0-9]{0,3}( |-)?[0-9]{4}( |-)?[0-9]{3}( |-)?[0-9]{3}, case 0, canon 0))'

Jignesh Mayani
  • 6,937
  • 1
  • 20
  • 36
Chengappa C D
  • 1,841
  • 1
  • 12
  • 19
  • http://stackoverflow.com/questions/3349494/objective-c-regex-to-check-phone-number – Laxmi Nov 27 '13 at 07:52
  • A simple one.. If this could help: http://www.iossnippet.com/snippets/validation/how-to-validate-a-phone-number-in-objective-c-ios/ – GenieWanted Nov 27 '13 at 07:59

3 Answers3

3

+ is a special character; you need to escape it (\+?) or use it properly (e.g. \s+? for leading spaces)

Me again
  • 496
  • 2
  • 10
0

Use the pattern like this

regExpPattern=@"(([+]{1}|[0]{2}){0,1}+[1]{1}){0,1}+[ ]{0,1}+(?:[-( ]{0,1}[0-9]{3}[-) ]{0,1}){0,1}+[ ]{0,1}+[0-9]{2,3}+[0-9- ]{4,8}";
Vizllx
  • 9,135
  • 1
  • 41
  • 79
0

I meet this problem too. '+' is indeed a meta character,you should understand why you use '+'.

If you want to match '+' like a normal character.then you should use '\+'.

If you treat the '+' like special character,want to match one other character.then you should add the character before '+',then it will not crash.

PS: in iOS predicate the 'like' and 'matches' do not conform same regex match rule!

frank
  • 2,327
  • 1
  • 18
  • 20