Reputation: 9522
I need to stop the user putting javascript into what should be a link field. I know I could just check for "javascript:" at the start of the url they enter, but I was wondering if there was some way I could construct the <a>
tag to force it to treat the href as an address? I feel like this would be a better solution, as people are always finding ways to get around basic checks.
Upvotes: 0
Views: 187
Reputation: 7997
First you should recognize that the browser can be manipulated into submitting whatever the user wants, so client-side validation is neither necessary nor sufficient, just convenient (to the user).
Given that, an easy process comes to mind:
Try this:
function validateUrl(value) {
return value.match(/^(http|https):\/\//) != null;
}
if(validateUrl(inputField.value)) {
// value is acceptable
} else {
// value is not an acceptable URL
}
Upvotes: 1
Reputation: 29831
You could always prepend the http:// or https:// protocol. May require a replace to remove any existing http or https.
Even if you have
http://javascript:alert('test');
the javascript will not run.
Upvotes: 1
Reputation: 7727
Better whitelist than blacklist and check for http(s) protocol, I'd guess.
Upvotes: 1
Reputation: 31554
A funny solution (and very effective if you ask me), is to put http://
in front of urls that don't already start with it. This is a sketch of what I mean:
if(url.slice(0,"http://".length) !== "http://" && url.slice(0,"https://".length) !== "https://") {
url = "http://" + url;
}
Upvotes: 3
Reputation: 21466
There is no pure HTML way of forcing the tag to treat the href as a URL.
The only thing (I know of) that you can do is check for javascript in the href attribute.
Upvotes: 0