How to detect external urls using Javascript
My objective is simple, I'm kind of surprised that i can't find an answer to this in other posts, i apologize in advance if i missed it....
I have a textarea input. I want to 开发者_JS百科make sure users don't post links to external sites.
I prefer to do this client side and simply prevent submission if external link is present.
I have seen numerous posts on how to find urls and make them into href's. I suppose i can use the same logic to simply remove them, but that will not prevent the users from proceeding, what i want to do is specifically stop them for submitting if external links are present.
I also need to allow for links within the same domain, so the actual url of detected links must be compared as well. I've seen ways to do this once i have the url in a string on its own, but right now, it is somwhere in the middle of a parapraph of text.
<script type="text/javascript">
function validate() {
var noExternalURLs = true;
var currentDomain = window.location.protocol + '//' + window.location.host;
var links = new Array();
var re = new RegExp('^'+currentDomain,"gi");
// Get protocol & domain of URLs in text
links = document.getElementById('mytextbox').value.match(/(https?:\/\/[\w\d.-]+)/gi);
// Loop over links. If protocol & domain in URL doesn't match current protocol & domain then flag
for(var i=0; i<links.length; i++)
{
if( links[i].match(re) == null )
{
noExternalURLs = false;
}
}
return noExternalURLs; // prevent submit if noExternalURLs==false
}
</script>
<form id="myform" action="index.php" onsubmit="return validate();">
<textarea id="mytextbox"></textarea>
<input type="submit" />
</form>
Do not do this client side only. You must check server side too. Client side checks are only for improving the user experience. Any business logic MUST be handled on he server side.
It is trivial to do this as post or get:
http://url.com?textareainput=http://urltoverybadsite
You can make it nicer for your users by doing a quick regex:
<script>
function checkLinks()
{
var links = document.getElementById('textareainput').value.match("/http:\/\//")
if (!links)
{
window.alert("Links not allowed!")
return false;
}
return true;
}
</script>
<form onsubmit="checkLinks()"><textarea id='textareainput'></textarea></form>
精彩评论