Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

URL validation in Swift

Tags:

ios

swift

In my Swift iOS project, I want to check whether is the valid url or not before requesting to server. I did earlier in Objective C code to check many elements like presence of www, http, https, :, etc to validate whether the right url or not. Do we have anything similar in Swift code?

I am expecting like this Obj C method.

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

Please suggest.

like image 847
Stella Avatar asked Mar 17 '15 17:03

Stella


People also ask

How do you validate a URL?

You can use the URLConstructor to check if a string is a valid URL. URLConstructor ( new URL(url) ) returns a newly created URL object defined by the URL parameters. A JavaScript TypeError exception is thrown if the given URL is not valid.

What is URL in Swift?

A value that identifies the location of a resource, such as an item on a remote server or the path to a local file. iOS 7.0+ iPadOS 7.0+ macOS 10.9+ Mac Catalyst 13.0+ tvOS 9.0+ watchOS 2.0+ Xcode 8.0+


1 Answers

Swift 4.x

This Covers all types of validation like Subdomain, with or without HTTP / HTTPS

func isValidUrl(url: String) -> Bool {
    let urlRegEx = "^(https?://)?(www\\.)?([-a-z0-9]{1,63}\\.)*?[a-z0-9][-a-z0-9]{0,61}[a-z0-9]\\.[a-z]{2,6}(/[-\\w@\\+\\.~#\\?&/=%]*)?$"
    let urlTest = NSPredicate(format:"SELF MATCHES %@", urlRegEx)
    let result = urlTest.evaluate(with: url)
    return result
}

Hope this works for you.

like image 193
Ashu Avatar answered Nov 15 '22 06:11

Ashu