简体   繁体   English

如何强制用户只放数字

[英]How to force the user to put only numbers

我希望用户只能使用输入数字我已经尝试了几件事,比如oninput="this.value = this.value.replace(/[^0-9.]/g, '')和很多更多,但例如我发送的代码,如果我键入一个字母,并继续按键盘上的字母,它不会把它变成任何东西,我需要一个代码,将100%强制用户只键入数字无所谓如果我可以在用户不能删除的输入框中输入一个数字,例如0,那就好了。

您可以使用输入规范中提到的<input type=...>

There are a few different ways to accomplish this but one of them would be capturing the keypress itself and returning false if the input is not a number. 有几种不同的方法可以实现这一点,但其中一种方法是捕获按键本身,如果输入不是数字则返回false

Also if I understand you correctly, to add a default value of "0", just define it in the input directly like value="0" , or you could use a placeholder="0" if that's what you're looking for. 另外,如果我理解正确,要添加默认值“0”,只需在输入中直接定义它,如value="0" ,或者你可以使用placeholder="0"如果这是你正在寻找的。

 <input type="number" value="0" onkeydown="javascript: return event.keyCode === 8 || event.keyCode === 46 ? true : !isNaN(Number(event.key))" /> 

While this wouldn't enforce the user input to numbers only, you may want to consider using the pattern attribute to leverage some built-in behaviour. 虽然这不会强制用户仅输入数字,但您可能需要考虑使用pattern属性来利用某些内置行为。 If you type non-numeric characters, the text colour will turn red: 如果键入非数字字符,文本颜色将变为红色:

 input:invalid { color: red; } 
 <input type="text" pattern="[0-9]+"/> 

Then we can start looking at the constraint validation API : 然后我们可以开始查看约束验证API

The Constraint Validation API enables checking values that users have entered into form controls, before submitting the values to the server. 在将值提交到服务器之前,Constraint Validation API允许检查用户输入表单控件的值。

If you type non-numeric characters and try to submit the form, you should see a built-in tooltip displaying a custom error message: 如果您键入非数字字符并尝试提交表单,您应该会看到显示自定义错误消息的内置工具提示:

 const input = document.querySelector('input'); input.addEventListener('invalid', () => { if (input.validity.patternMismatch) { input.setCustomValidity('Numbers only please!!'); } }); 
 input:invalid { color: red; } 
 <form> <input type="text" pattern="[0-9]+"/> <button type="submit">submit</button> </form> 

  $("#but").click(function(){ let inp_val = $("#txt").val(); if(isNaN(inp_val)){ alert("Just enter a number."); $("#txt").val(""); } }) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="text" id="txt"> <input type="button" value="CLICK" id="but"> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM