javascript 限制用户输入特殊字符和数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10117821/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 08:45:04  来源:igfitidea点击:

Restrict users from entering special characters and numbers

phpjavascriptvalidation

提问by Febin Thomas

How can I restrict users from entering special characters and numbers in the text box. I want only alphabets to be entered ( Typed / Pasted ).

如何限制用户在文本框中输入特殊字符和数字。我只想输入字母(键入/粘贴)。

give me sample javascript codes?

给我示例 javascript 代码?

回答by tcole

Take a look at this question: Function to return only alpha-numeric characters from string?

看看这个问题:Function to return only alpha-numeric characters from string?

This is what you're after:

这就是你所追求的:

$result = preg_replace("/[^a-zA-Z0-9]+/", "", $inputVar);

If you're inserting that into the database after that, be sure to use something like mysql_real_escape_string()or prepared statements.

如果您在此之后将其插入到数据库中,请确保使用类似mysql_real_escape_string()或准备好的语句。

Relying on Javascript solely for character validation is a very bad practice since JS can easily be disabled, and is not enabled on all devices globally.

仅依靠 Javascript 进行字符验证是一种非常糟糕的做法,因为 JS 很容易被禁用,并且并非在全球所有设备上都启用。

回答by RobG

Rather than preventing the entry of certain characers, it is far more user friendly and effective to validate the value when the form is submitted. You really don't care what the value of the field is before that, and you don't need special handling for how the value is entered. It might be pasted, dragged, auto-entered, entered by a plugin or script, or other methods.

与其阻止某些字符的输入,不如在提交表单时验证该值更加用户友好和有效。在此之前,您真的不关心字段的值是什么,并且您不需要对如何输入值进行特殊处理。它可能被粘贴、拖动、自动输入、通过插件或脚本或其他方法输入。

A trivial example:

一个简单的例子:

</script>

<form onsubmit="return validate(this);">
  <input type="text" name="foo">
  <input type="submit">
</form>

<script type="text/javascript">
function validate(form) {
  var re = /^[a-z,A-Z]+$/i;

  if (!re.test(form.foo.value)) {
    alert('Please enter only letters from a to z');
    return false;
  }
}
</script>

回答by SuperNoob

You can try this, I'm using this right now for my current project

你可以试试这个,我现在在我当前的项目中使用它

$(document).ready(function(){

/* Allow integers only in form input field with id #selector */
$('#selector').keyup(function () { 
    this.value = this.value.replace(/[^0-9\.]/g,'');
  });   
 })

It also doesn't allow the copy paste, but the weakness is the right click then paste

它也不允许复制粘贴,但弱点是右键单击然后粘贴

Disclaimer: I just found it from the internet

免责声明:我是从网上找到的