gpt4 book ai didi

javascript - 如何防止在表单中输入无效字符?

转载 作者:行者123 更新时间:2023-11-28 09:15:24 24 4
gpt4 key购买 nike

例如,如果我有一个表单,并且不希望用户在其中输入数字,并且我使用包含正则表达式的函数对其进行验证,那么如何防止用户输入的无效字符(在此示例中) ,一个数字)如果未通过正则表达式测试,是否会以文本形式显示?

这是我尝试过的功能和我尝试过的选择列表(换句话说,这不是整个程序)。我尝试向 onkeypress 事件处理程序返回 false,但用户在文本框中输入的内容仍然会执行。

function noNumbers(answer) {  //returns false and displays an alert if the answer contains numbers
if (/[\d]+/.test(answer)) { // if there are numbers
window.alert("You can not enter numbers in this field");
return false;
}

}

<form action="get" enctype="application/x-www-form-urlencoded">
<select id="questions" name="questions">
<option value="no_numbers">What is the name of the city where you were born?</option>
<option value="no_letters">What is your phone number?</option>
<option value="no_numbers">What is the name of your favorite pet?</option>
<option value="no_letters">What is your social security number?</option>
<option value="no_numbers">What is your mother's maiden name?</option>
</select>
<p><input type="text" name="answer" onkeypress="validateAnswer();" /></p>
</form>

最佳答案

当您在相关字段中输入无效字符时,此验证非常适合即时删除无效字符。示例:

<form id="form1" name="form1" method="post">
Email:
<input type="text" name="email" id="email" onkeyup='res(this, emailaddr);' ; </form>

<script>
var phone = "()-+ 0123456789";
var numb = "0123456789";
var alpha = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ @-'.,";
var alphanumb = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ @-.'1234567890!?,:;£$%&*()";
var alphaname = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ,-.1234567890";
var emailaddr = "0123456789@._abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

function res(t, v) {
var w = "";
for (i = 0; i < t.value.length; i++) {
x = t.value.charAt(i);
if (v.indexOf(x, 0) != -1)
w += x;
}
t.value = w;
}
</script>

然后,您只需使用代码中定义的变量将 javascript 调用的第二个值更改为您想要在字段中输入的数据类型。

关于javascript - 如何防止在表单中输入无效字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15727627/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com