![](/img/trans.png)
[英]How to restrict user to enter only 2digits only (hours in a day) in textbox using javascript
[英]How to restrict user to enter only numbers and enter key in textarea using javascript?
我对 Javascript 很陌生。
我要求only digits and enter key as input in a textarea box
允许only digits and enter key as input in a textarea box
。 我还希望允许用户paste ONLY digits into the textarea
。
在 StackOverflow 上搜索问题后,我发现了以下内容:
function validate(key)
{
//getting key code of pressed key
var keycode = (key.which) ? key.which : key.keyCode;
var phn = document.getElementById('textarea');
//comparing pressed keycodes
if (keycode < 48 || keycode > 57)
{
return false;
}
<div>
<textarea id="textarea" rows="4" cols="50" onkeypress="return validate(event)" />
</div>
不幸的是,这并不能完全解决我的问题。 我想允许用户按enter
。 如何更改上面的代码以允许“输入”按下以及整数粘贴事件?
这是一个非常简单的修改。 只需在您的代码中添加“等于”语句即可。 此外,由于您还想处理粘贴事件,因此您需要一个事件侦听器和“onPaste”函数。
方法 1:使用“onPaste”事件
function validatepaste(e) {
var pastedata = e.clipboardData.getData('text/plain');
if (isNaN(pastedata)) {
e.preventDefault();
return false;
}
}
function validate(e) {
//getting key code of pressed key
var keycode = (e.which) ? e.which : e.keyCode;
var phn = document.getElementById('textarea');
//comparing pressed keycodes
if ((keycode < 48 || keycode > 57) && keycode !== 13) {
e.preventDefault();
return false;
}
}
这是一个工作小提琴
这里有一些关于“onPaste”事件的信息。
方法 2:使用“onKeyUp”代替“onPaste”和“onKeyPress”
这种方法不太优雅,但如果您的环境不支持“onPaste”,它就可以工作
function validate(e) {
var invalidcharacters = /[^0-9]/gi
var phn = document.getElementById('textarea');
if (invalidcharacters.test(phn.value)) {
newstring = phn.value.replace(invalidcharacters, "");
phn.value = newstring
}
}
<div>
<textarea id="textarea" rows="4" cols="50" onKeyUp="validate(event)"></textarea>
</div>
还有一个jsfiddle
您的 if 语句应该类似于 if( keycode == 13 || keycode > x1 AND keycode < x2 || keycode > y1 AND keycode < y2) 给出有效输入,否则无效输入
其中 x 是数字的数字范围,y 是字符的数字范围。
function validate(){
const input = document.getElementById("input")
const regex = /[^0-1|\n\r]/g
input.value = input.value.split(regex).join('');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.