JavaScript输入验证以防止在文本框中输入URLs

huangapple go评论61阅读模式
英文:

Javascript Input Validation For Preventing URLS in TextBox

问题

Sure, here's the translation of the code part you provided:

如果文本框区域为空已经有下面的代码来确保它不为空我想添加另一段代码如果用户输入URL不允许提交表单例如我希望阻止使用http我尝试过如何实现这一点但没有成功

这是我用来确保文本框区域不为空的代码请复制并粘贴它然后帮助我找出如何添加另一个条件以防止表单中包含http

if (document.frmMailingList.txtaKnowledge.value == "")
{
alert("请包括您是如何知道我们的信息!");
document.frmMailingList.txtaKnowledge.focus();
return false;
}


我一直没有能够解决这个问题。

If you have any further questions or need assistance with adding the condition to block URLs, please let me know.

英文:

I already have the below code for making sure the text box area is not empty. I would like to add another code that would not allow the form to be submitted if the person enters urls. For example, I want http to be blocked. I have tried to figure out how to do this, but I have been unsuccessful.

Here's my code for making sure the textbox area is not empty. Please copy and paste it and help me to figure out how to add another condition that does not allow the form to be submitted if there is http.

		
    if (document.frmMailingList.txtaKnowledge.value == "")
	{
		alert("Please include how you heard about us!");
		document.frmMailingList.txtaKnowledge.focus();
		return false;
	}	

I have not been able to figure this out.

答案1

得分: 1

尝试将文本解析为URL,如果抛出错误,则知道它不是有效的URL。

var isUrl = true;
try {
    new URL(document.frmMailingList.txtaKnowledge.value)
} catch(error) {
    isUrl = false
}

if (document.frmMailingList.txtaKnowledge.value == "" && !isUrl) {
    alert("请说明您是从哪里得知我们的信息!");
    document.frmMailingList.txtaKnowledge.focus();
    return false;
}
英文:

One way to do it is to try and parse the text into a url, and if it throws an error, then you know it is not a valid url.

var isUrl = true;
try {
    new URL(document.frmMailingList.txtaKnowledge.value)
} catch(error) {
    isUrl = false
}

if (document.frmMailingList.txtaKnowledge.value == "" && !isURL) {
    alert("Please include how you heard about us!");
    document.frmMailingList.txtaKnowledge.focus();
    return false;
} 

huangapple
  • 本文由 发表于 2023年5月11日 01:15:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/76221049.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定