Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

URL Validation (Objective-C)

I am trying to validate a URL with this method:

Code:

- (BOOL) validateUrl: (NSString *) candidate {

    NSString *urlRegEx=
    @"((https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\))+[\w\d:#@%/;$()~_?\+-=\\\.&]*)";

    NSPredicate *urlTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", urlRegEx]; 
    return [urlTest evaluateWithObject:candidate];

}

It does not function. I think the problem is with the regular expression.

like image 399
saleh Hosseinkahni Avatar asked Nov 22 '11 09:11

saleh Hosseinkahni


3 Answers

You can use + (id)URLWithString:(NSString *)URLString method of NSURL, which returns nil if the string is malformed.

Use if (URL && URL.scheme && URL.host) for checking URL.

like image 70
Parag Bafna Avatar answered Oct 12 '22 23:10

Parag Bafna


Try with this..

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

it may help u out.

like image 30
iCoder4777 Avatar answered Oct 12 '22 23:10

iCoder4777


What about using the following:

NSURL * url = [NSURL URLWithString:@"http://www.google.com"];

BOOL isValid = [UIApplication.sharedApplication canOpenURL:url];

note: best practice is to use regex

like image 44
Amr Angry Avatar answered Oct 13 '22 01:10

Amr Angry