【问题标题】:Avoid special characters js or Angular避免特殊字符 js 或 Angular
【发布时间】:2018-01-10 16:27:22
【问题描述】:

我需要避免使用 js 输入特殊字符,在按键或 keydown 时。我正在尝试不同的方式,但 de 字符 ^ 或 Ç 总是赢。请帮忙!

【问题讨论】:

  • 请提供minimal reproducible example,包括输入和预期结果以及适当详细的问题描述
  • 如果您使用的是 Angular,您可以使用模式验证器,例如正则表达式。
  • 如果有人是 SO 新手,请不要直接对问题投反对票。伸出你的手和时间来帮助他们。我在这里添加了示例代码及其解决方案。

标签: javascript angular


【解决方案1】:

要限制onkeypress事件的特殊字符,请按照以下方式进行。

Plunkr

<!DOCTYPE html>
<html>
<body>

<p>A function is triggered when the user is pressing a key in the input field.</p>

<input type="text" onkeypress="myFunction(event)">

<script>
function myFunction(e) {
    var x = e.which || e.keyCode;//depends on browser support
    if((x >= 48 && x <= 57) || (x >= 97 && x <= 122) || (x >= 65 && x <= 91))
    {
        //your code goes here
    }else e.preventDefault();
}
</script>

</body>
</html>

如果有帮助,请告诉我们。

【讨论】:

  • 它允许`+´ç¨Ç^ 感谢您的回答。
  • 我不知道字符 ç¨Ç,但上面的示例不允许使用 '+' 和 '^'。我提供了一个 Plunker 示例。请检查一下。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-06-26
  • 2014-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多