0

I need to check if the provided URI is valid, this URI can be a hostname, localhost, a IP address, a hostname with a port.

Here is my current regular expression:

isValidURI = function(uri){
  return new RegExp("^((cc:|https:|http:|[/][/]|www.)([a-z]|[A-Z]|[0-9]|[/.])*)$", 'g').test(uri);
}

var urls = [
  'http://localhost',
  'http://localhost.com',
  'http://www.localhost.com',
  'http://www.localhost.com:8080',
  'cc://custom.Data',
  'https://www.localhost.com',
  'https://localhost',
  'http://local host ',
  'localhost',
  'notvalid',
  'http://sjc1dsppf09.crd.ge.com:9090/service/dummydata/bar'
];  



for( var i=0; i < urls.length; i++){
  var valid = isValidURI(urls[i]);
  if(valid){
    console.log( urls[i] + ' - [isValid = ' + valid + ']') 
  } else {
    console.error( urls[i] + ' - [isValid = ' + valid + ']') 
  }
}

And here is the output:

"http://localhost - [isValid = true]"
"http://localhost.com - [isValid = true]"
"http://www.localhost.com - [isValid = true]"
"http://www.localhost.com:8080 - [isValid = false]"
"cc://custom.Data - [isValid = true]"
"https://www.localhost.com - [isValid = true]"
"https://localhost - [isValid = true]"
"http://local host  - [isValid = false]"
"localhost - [isValid = false]"
"notvalid - [isValid = false]"
"http://sjc1dsppf09.crd.ge.com:9090/service/dummydata/bar - [isValid = false]"

I need the urls with :port to be valid, what am I doing wrong?

Here is a link to the JSBin.

http://jsbin.com/AYUpENAJ/3/edit?js,console,output

Jonnie
  • 43
  • 1
  • 4

2 Answers2

2
new RegExp("^(cc|https?)://([a-zA-Z\.]*(:[0-9]*)?(?:/[a-zA-Z0-9]*)*)?$", 'g').test(uri);

If you need http://sjc1dsppf09.crd.ge.com:9090/service/dummydata/bar to be valid, use:

new RegExp("^(cc|https?)://([a-zA-Z0-9.](:[0-9])?(?:/[a-zA-Z0-9]))?$", 'g').test(uri);

If you need the to be able to use www. without a protocol, then replace the first group with

(?:(cc|https?):|www.)
adamdc78
  • 1,123
  • 8
  • 18
  • The middle RegExp doesn't appear to render correctly for me; it should be `^(cc|https?)://([a-zA-Z0-9\.]*(:[0-9]*)?(?:/[a-zA-Z0-9]*)*)?$` but renders as `^(cc|https?)://([a-zA-Z0-9.](:[0-9])?(?:/[a-zA-Z0-9]))?$` with italics in the middle. – adamdc78 May 24 '18 at 21:59
1

There is no check for the colon : , the following passes your tests,

new RegExp("^((cc:|https:|http:|[/][/]|www.)([a-z]|[A-Z]|[:0-9]|[/.])*)$", 'g').test(uri);

http://jsbin.com/eJIJEWUC/1/edit

melc
  • 11,373
  • 2
  • 30
  • 39