英文:
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;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论