0

Working on an app that validates a URL before accepting the submission.

The follow code accepts simple urls such as www.google.com, but does not worth with more complex urls such as www.google.com/?test-test

- (BOOL) validateUrl: (NSString *) candidate {
    NSString *urlRegEx =
    @"((\\w)*|([0-9]*)|([-|_])*)+([\\.|/]((\\w)*|([0-9]*)|([-|_])*))+";
    NSPredicate *urlTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", urlRegEx];
    return [urlTest evaluateWithObject:candidate];
}
rmaddy
  • 307,833
  • 40
  • 508
  • 550

1 Answers1

0

Cited from Apple documentation:

Return Value An NSURL object initialized with URLString. If the URL string was malformed or nil, returns nil.

You can test validity of URL by actually trying to make a NSURL object.

NSString* some_url1 = ...// your input
NSURL* u1 = [NSURL URLWithString:some_url1];
BOOL ok = u1 != nil;
eonil
  • 79,444
  • 75
  • 307
  • 502