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
  • 314,917
  • 42
  • 532
  • 579

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
  • 83,476
  • 81
  • 317
  • 516