如何在文本框中仅输入数字和减号( - )? [英] How can I enter only number and minus(-) sign in a text box?

查看:67
本文介绍了如何在文本框中仅输入数字和减号( - )?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用负数验证数字输入,我该怎么做?









谢谢

I would like to validate the numeric input with negative number, how can I do that?




Thanks

推荐答案

首先,请参阅这个简单的教程,详细了解使用JavaScript的输入控件过滤和更好的代码: http://www.javascripter.net/faq/keyboardinputfiltering.htm [ ^ ]。



另外,这些是用于找出要过滤的内容的非常有用的资源:

http:/ /www.asquare.net/javascript/tests/KeyCode.html [ ^ ],

http://unixpapa.com/js/testkey html的 [ ^ ]。



解决方案1为您提供了正确的想法,但遗憾的是,它并未解决问题。它会过滤掉除减号,十进制数字和退格之外的所有内容(重要的是:8)。但最重要的是,无论如何都需要进行一些验证。这是因为减号可能被错放或添加两次,或者数字位数可能太大,换句话说,输入仍然无效。此外,您可能需要另外检查一些所需范围的数据。



因此,如果没有验证,您将无法逃脱。验证的最佳初始步骤是将字符串实际解析为数字。除了验证之外,您还将获得您应该使用的数字本身。请参阅:

https://developer.mozilla .org / zh-CN / docs / Web / JavaScript / Reference / Global_Objects / parseInt [ ^ ]。



现在你只需处理数字输入您的情况。



-SA
First of all, please see this simple tutorial on more detail on input control filtering with JavaScript with better code: http://www.javascripter.net/faq/keyboardinputfiltering.htm[^].

Also, these are the very useful resources used to find out what to filter:
http://www.asquare.net/javascript/tests/KeyCode.html[^],
http://unixpapa.com/js/testkey.html[^].

Solution 1 gives you the right idea, but, unfortunately, does not solves the problem. It does filter out all except minus sign, decimal digits and backspace (important thing: 8). But on top of it, you need some validation anyway. This is because minus sign can be misplaced or added twice, or the number of digits can be too big, in other words, the input still can be invalid. Besides, you may need to additionally check up the data for some required range.

Therefore, you cannot get away without the validation. The best initial step of validation would be to actually parse the string into number. In addition to the validation, you will get the number itself, which you should use. Please see:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt[^].

Only now you got everything to deal with numeric input in your case.

—SA


您可以使用以下脚本:

You can use the script as below:
<div>
    <input id="txtNum" type="text" onkeydown="functionAllNum();" />
</div>

<script>
    function functionAllNum() {
        var num = document.getElementById("txtNum").value;
        if (num == "") {
            if ((event.keyCode < 48 || event.keyCode > 57) && event.keyCode != 189) {
                event.preventDefault();
                alert("Please Enter Number Only");
            }
        } else {
            if ((event.keyCode < 48 || event.keyCode > 57) && event.keyCode != 8) {
                event.preventDefault();
                alert("Please Enter Number Only");
            }
        }
    }
</script>


这篇关于如何在文本框中仅输入数字和减号( - )?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆