Jamie Penney
Jamie Penney

Reputation: 9522

Preventing the user from entering javascript instead of a url for use in an href

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

Answers (5)

Jesse Dhillon
Jesse Dhillon

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:

  • Enforce that every URL is absolute by requiring a protocol spec at the beginning of the URL.
  • Enforce that the protocol is one of {http, https}.

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

Josiah Ruddell
Josiah Ruddell

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

Ulrich Schwarz
Ulrich Schwarz

Reputation: 7727

Better whitelist than blacklist and check for http(s) protocol, I'd guess.

Upvotes: 1

Gabi Purcaru
Gabi Purcaru

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

simshaun
simshaun

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

Related Questions