1

I have an application where users have somewhat of a settings page, and some of those settings allow URLs to be entered into them. I want to be able to run a check using javascript to make sure the URL they entered is valid and a real URL.

When they click submit, it will either do what it's supposed to do, or if there's an error in the URL, pop up with an alert and say "Invalid URL entered!".

Is there a way to do this with JS? I also want this script to work with http:// and https:// as well as www. in the URL, and every domain extension (.com, .tv, etc.). This also needs to be done with JavaScript, not jQuery.

Can anyone show me how to do this? Thanks.

Jared
  • 2,006
  • 4
  • 23
  • 43
  • 2
    I'd look at http://stackoverflow.com/questions/161738/what-is-the-best-regular-expression-to-check-if-a-string-is-a-valid-url – Ivan Oct 28 '11 at 04:41

1 Answers1

2

It seems you're wanting to do two things:

1) Determine that the URL is valid (i.e. correctly formatted)

For this a regular expression will work well, this approach will also allow you to retrieve various parts of the URL if that's something you'd like to do.

this has been discussed here: What is the best regular expression to check if a string is a valid URL?.

2) Determine that the URL is real (i.e. if someone where to follow it they'd find something)

This is more tricky, but you could attempt an AJAX request to the URL and if it fails or times out assume it's down. There may be some limitations to this approach due to XSS security features on sites.

If that's a problem you could create a service of your own design that runs on a server that your JavaScript makes a request to, passing it the URL, and it responds with a failure or success.

Here's an example:

verify.js

function verifyURL (url) {
    // with jQuery
    $.getJSON('check-url.cgi', { url : url }, function (res) {
        console.log(res); // display server response
            if ( res.status == 'success' ) {
               // URL is real
            } else {
               // URL is not real
            }
    });
}

check-url.cgi

#!/usr/bin/env perl
use v5.10;
use strict;
use warnings;

use CGI qw(:standard);
use JSON::XS;
use LWP::UserAgent;

my $ua = LWP::UserAgent->new;
$ua->agent("URL Checker/0.1");

my $url    = param('url');
my $req    = HTTP::Request->new(GET => $url);
my $res    = $ua->request($req);
my $status = $res->is_success ? 'success' : 'failure';

print header('applicaton/json'), encode_json { status => $status };
Community
  • 1
  • 1