I assume, that you know how to get the value of <input>
with JavaScript. So your problem is writing the specific function for validating the URL.
First we might consider checking that the URL is syntactically correct.
Some examples, that our URL validator should definitely consider OK:
http://www.example.com.
http://www.google.ee/search?q=foo&sourceid=opera&ie=utf-8&oe=utf-8
https://ama-z-on.co.uk/index.html?a=hei%20hoo
ftp://ftp.linux.ee/public/gentoo/i386/portage-snapshot.tar.bz
http://he.wikipedia.org/wiki/????????#.D7.A8.D7.90.D7.95_.D7.92.D7.9D
sftp://123.1.255.128:80/pub
And that's only a small fraction of the real variety of URL-s possible. And HTTP and FTP aren't the only protocols possible for URL. Oh man, that URL-validation is really hard.
But lets assume that a valid URL should start with some letters, then "://" and after that what ever. To test that kind of pattern you would use a regular expression which in JavaScript looks like this:
function validateUrl(url) {
return /^[a-z]+:///i.test(url);
}
Regular expressions are a whole big topic, that you should consider learning by yourself, but just a brief explanation here:
/
- start of regular expression
^
- matches the beginning of string
[a-z]
- matches either a, b, c, ..., x, y, or z.
+
- means that the previous pattern can be repeated one or more times.
:
- matches the colon symbol itself.
/
- matches forward-slash /
(without the backslash JavaScript would think it's the end of regular expression).
/
- ends the regular expression.
i
- this is a modifier, that makes this regular expression case-insensitive.
.test(url)
- calls the test
method of regular expression object with url
as the parameter. When parameter matches the regular expression, it returns true
otherwise false
.
Additionally you might want to allow entering an URL without the http://
part - this means you really need to validate the domain name or IP address or whatever that follows it.
I guess you are pretty confused by now, and that's intentional. You really shouldn't write JavaScript to do URL validation by yourself, it's too hard to get it right. Instead you should use a library function, that is tested and confirmed to be correct by many experts.
Maybe the JavaScript fraimwork you are using already has a good tool for that job. In that case use it. Unfortunately I can not suggest any specific library for URL validation specifically.
Additionally you might want to consider pinging the URL as Josh Stodola suggested, to check that it really exists. Although, the particular way Josh suggest, might be problematic in case the resource referenced by URL is 10GB file :)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…