Skip to content
This repository was archived by the owner on May 30, 2022. It is now read-only.

Commit

Permalink
fix(util): Updated the url regex to be more verbose—more inline with …
Browse files Browse the repository at this point in the history
…rfc3986. Modified the protocol attribute to return only the protocol.

Close #134
  • Loading branch information
Carey Hinoki authored and adrianlee44 committed Nov 4, 2013
1 parent 20f2282 commit 5d57301
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 9 deletions.
31 changes: 24 additions & 7 deletions src/util.coffee
Original file line number Diff line number Diff line change
Expand Up @@ -143,19 +143,36 @@ angular.module("Mac.Util", []).factory "util", [

return rgb

_urlRegex: /(?:(?:(http[s]{0,1}:\/\/)(?:(www|[\d\w\-]+)\.){0,1})|(www|[\d\w\-]+)\.)([\d\w\-]+)\.([A-Za-z]{2,6})(:[\d]*){0,1}(\/?[\d\w\-\?\,\'\/\\\+&%\$#!\=~\.]*){0,1}/i
# http://tools.ietf.org/html/rfc3986#section-2.2
_urlRegex: ///
(?:
(http[s]?):// # protocol (optional)
)?
(?:
(www|[\d\w\-]+)\. # subdomain (optional)
)?
([\d\w\-]+)\. # domain
([A-Za-z]{2,6}) # tld
(:[\d]*)? # port (optional)
([ # path (optional)
:/?#\[\]@ # rfc3986 gen-delims
!$&'()*+,;= # rfc3986 sub-delims
\w\d-._~ # rfc3986 unreserved characters
%\\ # additional characters
]*)?
///i

validateUrl: (url) ->
match = @_urlRegex.exec url
if match?
match = {
url: match[0]
protocol: match[1] or "http://"
subdomain: match[2] or match[3]
name: match[4]
domain: match[5]
port: match[6]
path: match[7] or "/"
protocol: match[1] or "http"
subdomain: match[2]
name: match[3]
domain: match[4]
port: match[5]
path: match[6] or "/"
}
# Recreate the full url
match["url"] = match.url
Expand Down
13 changes: 11 additions & 2 deletions test/unit/util.spec.coffee
Original file line number Diff line number Diff line change
Expand Up @@ -115,14 +115,23 @@ describe "Mac Util", ->

it "should validate URL", ->
validUrl = "http://www.macgyver.com"

validObj = util.validateUrl validUrl
expect(validObj.protocol).toBe "http://"

expect(validObj.protocol).toBe "http"
expect(validObj.subdomain).toBe "www"
expect(validObj.name).toBe "macgyver"
expect(validObj.domain).toBe "com"
expect(validObj.path).toBe "/"

it "should validate complex URL", ->
validComplexUrl = "https://macgyver.io/cow/make/sound?sound=(moo)&andrian=cool#carey"
validComplexObj = util.validateUrl validComplexUrl

expect(validComplexObj.protocol).toBe "https"
expect(validComplexObj.subdomain).toBeUndefined()
expect(validComplexObj.domain).toBe "io"
expect(validComplexObj.path).toBe "/cow/make/sound?sound=(moo)&andrian=cool#carey"

it "should return null on invalid URL", ->
invalidUrl = "http://www"
expect(util.validateUrl invalidUrl).toBe null
Expand Down

0 comments on commit 5d57301

Please sign in to comment.