Jeet Chaudhary
Jeet Chaudhary

Reputation: 41

Validate url for iOS start with www

I want url start with www and end with any type like .com , .co etc

example - www.example.com or any other.

I tried

-(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];
}

But it works with http and https

Upvotes: 2

Views: 1013

Answers (2)

Jeet Chaudhary
Jeet Chaudhary

Reputation: 41

This Regex works for all the valid url with or without http ,https ,www.

Regex=@"(?i)\\b((?:[a-z][\\w-]+:(?:/{1,3}|[a-z0-9%])|www\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,4}/?)(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\))*(?:\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\)|[^\\s`!()\\[\\]{};:'\".,<>?«»“”‘’])*)";

Upvotes: 2

Jasper Blues
Jasper Blues

Reputation: 28746

Regular expressions are very powerful, but for this simple case how about two category methods.

@implementation NSString (SuffixTest)

- (BOOL)jc_startsWithAnyOf:(NSArray*)prefixes
{
    for (NSString *candidate in prefixes) {
        if ([self hasPrefix:candidate]) {
            return YES;
        }
    }
    return NO;
}

- (BOOL)jc_endsWithAnyOf:(NSArray *)suffixes
{
    for (NSString *candidate in suffixes) {
        if ([self hasSuffix:candidate]) {
            return YES;
        }
    }
    return NO;
}


@end

And then use as:

- (BOOL)isValidAddress:(NSString*)string
{
    return [string jc_startsWithAnyOf:@[@"http://www.", @"https://www."]] && 
        [string jc_endsWithAnyOf:@[@"com", @"org"]];
}

. . . a little more verbose, but at least doesn't require consulting the regular expression docs to understand the code.

Upvotes: 2

Related Questions