在以下情况下如何防止数值数据:HTML输入类型=“文本”?

时间:2018-08-23 00:06:32

标签: php html input

我目前有一个带有名字和姓氏文本字段的html / php注册页面设置,但我想防止输入数字数据(仅将输入限制为字母),这可能是一个重复的问题,但我只是研究时似乎找不到任何东西。如何防止用户输入数字?

<tr>
  <th> <label for = "firstname">Firstname </label> </th>
  <td> <input type = "text" name = "firstname" id = "firstname" value = "<?php echo isset($firstname)?$firstname:''; ?>" required /> </td>
</tr>

 <tr>
    <th> <label for = "lastname">Lastname </label> </th>
    <td> <input type = "text" name = "lastname" id = "lastname" value = "<?php echo isset($lastname)?$lastname:''; ?>"required /> </td>
 </tr>

1 个答案:

答案 0 :(得分:0)

这可以通过在javascript中使用Event Listener来实现。

因此,在keypress上,它将检查当前按下的键是否为字母之一。

在我的示例中,如果输入了非字母字母,我使用event.preventDefault()取消了按键。

Example

window.onload = function() {
  firstname = document.getElementById("firstname");
  //Listen for keypress in the firstname input
  firstname.addEventListener("keypress", function(e) {
    char_regex = RegExp('[A-Za-z]')
    //Prevent the key to be entered if it's not one of the alphabetic
    if(!char_regex.test(e.key)) {
      e.preventDefault();
    }
  })
}

但是,最好再次检查服务器代码中的输入。