// // Created by Calios on 2017-04-10. // Copyright © 2017 Calios. All rights reserved. // @implementation NSString (URLValidate) - (BOOL)isValidURL { if ([self isIPAddress]) { return [self isValidIPAddress]; } return [self isValidDNSAddress]; } - (BOOL)isValidDNSAddress { NSString *result = self; if (![self containsProtocol]) { result = [NSString stringWithFormat:@"http://%@",self]; } NSString *urlRegEx = @"(http|https)://((\\w)*|([0-9]*)|([-|_])*)+([\\.|/]((\\w)*|([0-9]*)|([-|_])*))+(:[0-9]{1,})?"; NSPredicate *urlTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", urlRegEx]; return [urlTest evaluateWithObject:result]; } - (BOOL)isIPAddress { NSString *result = self; if ([self containsProtocol]) { result = [result componentsSeparatedByString:@"//"].lastObject; } NSRegularExpression *regex = [[NSRegularExpression alloc] initWithPattern:@"[a-zA-Z]" options:0 error:NULL]; NSInteger matches = [regex numberOfMatchesInString:result options:0 range:NSMakeRange(0, result.length)]; return (matches <= 0); } - (BOOL)isValidIPAddress { NSString *result = self; if ([self containsProtocol]) { result = [result componentsSeparatedByString:@"//"].lastObject; } NSString *ipRegEx = @"(\\d{1,3}\\.){3}(\\d){1,3}(:\\d{1,})?"; NSPredicate *ipTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", ipRegEx]; return [ipTest evaluateWithObject:result]; } - (BOOL)containsProtocol { return [self hasPrefix:@"http://"] || [self hasPrefix:@"https://"]; } @end