例如,如果我有一个表单并且我不希望用户在其中输入数字并且我使用包含正则表达式的函数对其进行验证,我如何防止用户输入的无效字符(在此示例中为数字) 如果它没有通过正则表达式测试,它会不会出现在文本表单中?
这是我尝试过的功能和我尝试过的选择列表(换句话说,这不是整个程序)。我尝试将 false 返回到 onkeypress 事件处理程序,但用户输入到文本框中的内容仍然通过。
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>