javascript表单验证 - 仅限字母

时间:2018-04-03 15:14:43

标签: javascript html forms validation

我编写的代码只允许将字母输入到文本字段中,但它不起作用。你能帮我发现错误吗,请找一个解决方案。



function allLetter(inputtxt) {
  var letters = /^[A-Za-z]+$/;
  if(inputtxt.value.match(letters)){
      return true;
  }else{
      alert('Please input letters only');
      return false;
  }
} 

<form action="#" id="form1" name="form1" method="post">
  <input name="Forename" type="text" required="required" id="Forename2" onclick="allLetter(document.form1.text)"/>
</form>
&#13;
&#13;
&#13;

5 个答案:

答案 0 :(得分:3)

为什么不使用模式输入

<form action="#" id="form1" name="form1" method="post">
    <input name="Forename" type="text" required="required" id="Forename2" pattern="[A-Za-z]+" />
</form>

答案 1 :(得分:0)

document.form1.text不是访问文本输入字段的有效方式。 document.forms[0].elements['Forename']有效。尝试阅读MDN上的文档和表单对象以获取更多详细信息。

答案 2 :(得分:0)

您可以使用该模式执行您想要执行的操作。 https://www.w3schools.com/tags/att_input_pattern.asp

<form action="#" id="form1" name="form1" method="post">
    <input name="Forename" type="text" required="required" id="Forename2" pattern="^[A-Za-z]+$" />
</form>

但请注意,此类代码应在提交时验证服务器端。覆盖html输入模式和javascript是微不足道的。因此,服务器必须验证post上的所有输入。

您可以在那里试用https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_input_pattern

答案 3 :(得分:0)

您应该使用HTML模式属性。阅读它here

您必须注意,您的代码不会阻止用户在字段中输入内容,而只会警告他每次点击字段时他使用的符号都不对。您可以将其更改为onkeydown,这会使其更加清晰,但您仍然应该更喜欢上面提到的模式解决方案。

另请注意,来自客户端的每个数据都必须在服务器端进行检查,并且无法在客户端进行正确的清理(例如通过JS,HTML ... )。检查客户端只能用于改善用户体验,而不是用于提高安全性。

答案 4 :(得分:-1)

您可以将事件更改为onkeyup,因为onclick没有输入,也无法测试值。

然后你需要移交元素,最简单的方法是使用this作为对实际元素的引用。

对于搜索不想要的字符,您可以检查所需字符的整个字符串。

function allLetter(inputtxt) {
    var letters = /^[a-z]*$/i;
    if (!inputtxt.value.match(letters)) {
        alert('Please input letters only');
    }
}
<form action="#" id="form1" name="form1" method="post">
  <input name="Forename" type="text" required="required" id="Forename2" onkeyup="allLetter(this)" />
</form>