Html 限制在文本框中键入的字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3059559/
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
restrict a character to type in a text box
提问by Ben Rowe
how we can restrict a character to type in a text box.
我们如何限制一个字符在文本框中输入。
回答by Ben Rowe
You can do this via javascript (so if javascript is off, you won't be able to restrict it)
您可以通过 javascript 执行此操作(因此,如果 javascript 关闭,您将无法对其进行限制)
<input type="text" onkeyup="this.value = this.value.replace(/[^a-z]/, '')" />
This will restrict it to only a-z characters. Checkout regular expressionsto see what you can do
这会将其限制为仅 az 字符。查看正则表达式,看看你能做什么
回答by User 1034
If you have the text box then you have to handle the onkeypress
event
如果您有文本框,那么您必须处理该onkeypress
事件
<input type='text' onkeypress='keypresshandler(event)' />
You can use the following function to restrict the users
您可以使用以下功能来限制用户
function keypresshandler(event)
{
var charCode = event.keyCode;
//Non-numeric character range
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
}
回答by Jochem Schulenklopper
Although still possible, with HTML5 there's no real need to use a JavaScript-based solution for this requirement.
尽管仍有可能,但对于 HTML5,没有真正需要使用基于 JavaScript 的解决方案来满足此要求。
<input type="text" name="text" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$">
will restrict the allowed characters according that RegExp pattern (in this case: valid-looking email addresses).
<input type="text" name="text" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$">
将根据 RegExp 模式限制允许的字符(在这种情况下:有效的电子邮件地址)。
The title
attribute will be used as a warning / notification when the user tries to submit the data not matching the requirement.
title
当用户尝试提交不符合要求的数据时,该属性将用作警告/通知。
<form action="/add_country.php">
Country code: <input type="text" name="country_code" pattern="[A-Za-z]{3}" title="Three letter country code">
<input type="submit">
</form>
See the documentation on HTML input elementfor more information. Not all browsers support it equally well (like Safari) though.
回答by JW P
Ben Rowe's answer is indeed the way to approach it. However, the character will appear in the textbox before it is being removed. You can prevent that by using oninput
instead of onkeyup
:
Ben Rowe 的回答确实是接近它的方法。但是,该字符将在被删除之前出现在文本框中。您可以通过使用oninput
代替来防止这种情况onkeyup
:
<input type="text" oninput="this.value = this.value.replace(/[^a-z]/, '')" />
回答by Raman Singh
function isNumberKey1(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode;
if ( char!=8(charCode < 65 || charCode > 106))
return false;
return true;
}