Validate that a URL entered in a form is from a specific website with javascript
I have a website where people post links from Google+. I am trying to make sure that people can only post specific links from Google plus. An example would be, someone would need to post a link like https://plus.google.com/games/907809777960/params/%22%7B%5C%22encPrms%5C%22%3A%5C%22eyJiYXBpVGlja2V0SWQiOiI4MzFhNGQ0Ny0yYTU4LTQ2OTktYmI1Yy1hN2ExYTAzY2U4ZTMiLCJsYW5kaW5nUGFnZSI6Im5ld3NmZWVkL2JvbnVzYWJsZUZlZWQvbWFydmVsY29tcGxldGUvNTQ3Mjc3LzEzMTQ0NzA0MjUvMCIsInJlZl9pZCI6IjEwOTkyODAzNzUzNzQ2Mjk5NzAxMCIsInRyYWNrIjoibmV3c2ZlZWQtYm9udXNfbWFydmVsQ29tcGxldGUtMCIsInNlbmRfdGltZXN0YW1wIjoiMTMxNDQ3MDQyNyJ9%5C%22%7D%22/source/3. I want to make sure t开发者_运维知识库hat the link starts with or at least contains https://plus.google.com/games/907809777960/params/, if not, it will not submit the link and alert that the link is invalid. The code I have so far is.
<script type="text/javascript" language="JavaScript">
function checkForm(theForm) {
if (form.bonuslink.indexOf("https://plus.google.com/games/907809777960/params/") == -1)
{ alert('You can only enter authentic Google + links'); return false; }
else {
return true; }
}
</script>
<form action="submitbonus.php" onsubmit="return checkForm(this);" method="post">
Bonus Link: <input name="bonuslink" type="text" size="40" /> <input name="Submit" type="submit" value="Submit Bonus" /><br />
</form>
I cannot get it to work for some reason. It submits every time regardless of what it typed. I am not that familiar with javascript, so any help would be appreciated.
edit edit: you have two problems you need to reference the bonuslink value not the DOM element itself and you need to call it as a member of the 'theForm' instead of 'form' since that is what you called the parameter. Other than that everything should be fine.
<script type="text/javascript" language="JavaScript">
function checkForm(theForm) {
if (theForm.bonuslink.value.indexOf("https://plus.google.com/games/907809777960/params/") == -1){
alert('You can only enter authentic Google + links');
return false;
} else {
return true;
}
}
</script>
<form action="submitbonus.php" onsubmit="return checkForm(this);" method="post">
Bonus Link: <input name="bonuslink" type="text" size="40" /> <input name="Submit" type="submit" value="Submit Bonus" /><br />
</form>
this regular expression will extract the domain name from any string. basically it'll return the part starting from http:// etc.
/((https?|s?ftp|dict|www)(://)?)[A-Za-z0-9.\-]+)/gi
it'll detect the following forms:
- http://www.google.com
- https://www.google.com
- ftp://www.google.com
- dict://www.google.com
- www.google.com
enjoy.
精彩评论