0

I am allowing my users to insert a website url.

As you all know, some people are completely useless, typing whatever to the input, without any check.

I want to do a test on the user inputted url, to check if it is valid, and if not, repair it automatically using javascript, before displaying it to the public.

Example user submitted urls:

  • http://google.com
  • www.google.com
  • google.com
  • http//google.com
  • htp:/google.com
  • ++++++++

var web = user.url;

var urlCheck = /(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;

if(web){
    if(urlCheck.test(web) === false) {
        web = "http://" + web;
    }

    $('div.Link').html("<a href=\"javascript:void(0);\" onclick=\"externalLink('" + web + "');\">" + web + "</a>");
}

Suggestions on for an even better check/test to avoid problems?

t0mppa
  • 3,983
  • 5
  • 37
  • 48
Tom
  • 3,717
  • 5
  • 26
  • 28
  • 3
    Oh the irony. Mentions users "typing whatever to the input, without any check.", doesn't even check that his own question formats correctly ;) (yeah, someone else fixed it) – Jani Hartikainen Mar 09 '14 at 14:19
  • haha... there you go, my question is absolutely valid :) – Tom Mar 09 '14 at 14:28

1 Answers1

2

Try this

function is_valid_url(url)
{
     return url.match(/^(ht|f)tps?:\/\/[a-z0-9-\.]+\.[a-z]{2,4}\/?([^\s<>\#%"\,\{\}\\|\\\^\[\]`]+)?$/);
}

Call the is_valid_url(YOUR_WEBSITE_URL) function anywhere you want URL validation and it will return true or false

Source

Community
  • 1
  • 1
rsakhale
  • 1,018
  • 13
  • 26