JavaScript - 测试整数 [英] JavaScript - Test for an integer

查看:79
本文介绍了JavaScript - 测试整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本字段,允许用户输入他们的年龄。我正在尝试使用JavaScript在此字段上进行一些客户端验证。我已经有了服务器端验证。但是,我似乎无法验证用户输入的实际整数。我目前正在尝试以下代码:

I have a text field that allows a user to enter their age. I am trying to do some client-side validation on this field with JavaScript. I have server-side validation already in place. However, I cannot seem to verify that the user enters an actual integer. I am currently trying the following code:

    function IsValidAge(value) {
        if (value.length == 0) {
            return false;
        }

        var intValue = parseInt(value);
        if (intValue == Number.NaN) {
            return false;
        }

        if (intValue <= 0)
        {
            return false;
        }
        return true;
    }

奇怪的是,我在文本框中输入了单个字符,如b 并且此方法返回true。如何确保用户只输入整数?

The odd thing is, I have entered individual characters into the textbox like "b" and this method returns true. How do I ensure that the user is only entering an integer?

谢谢

推荐答案

更新

我修复了出错的代码并添加了一个名为 key 的var使用依赖于浏览器的 keyCode 来存储按键代码。

I have fixed the code that had an error and added a var called key to store the key pressed code using keyCode and which, that depend of the browser.

var key = e.which || e.keyCode;

谢谢Donald.McLean:)

Thanks Donald.McLean :)

如果你想在输入时检查你是否在写数字(并避免在输入字段中写入其他字符),你可以使用这个简单的函数,你可以定义允许的元素(这个包括你想要过滤的任何东西)。通过这种方式,您不仅可以选择整数,还可以选择某组字符。该示例基于jQuery将其附加到输入字段。

If you want to check if you are writing numbers while typing (and avoid writing other characters into your input field), you can use this simple function and you can define the elements allowed (this include whatever you want to filter). In this way you can choose not only integers but for example a certain group of characters. The example is based in jQuery to attach it to an input field.

$('#myInputField').keypress(function(e)
{
    var key = e.which || e.keyCode;

    if (!(key >= 48 && key <= 57) && // Interval of values (0-9)
         (key !== 8) &&              // Backspace
         (key !== 9) &&              // Horizontal tab
         (key !== 37) &&             // Percentage
         (key !== 39) &&             // Single quotes (')
         (key !== 46))               // Dot
    {
        e.preventDefault();
        return false;
    }
});

如果使用除定义之外的其他键,则不会出现在该字段中。而且因为Angular.js这些天变得越来越强大了。这是您可以在Web应用程序的任何字段中创建的指令:

If you use other key than the defined, it won't appear into the field. And because Angular.js is getting strong these days. this is the directive you can create to do this in any field in your web app:

myApp.directive('integer', function()
{
    return function (scope, element, attrs)
    {
        element.bind('keydown', function(e)
        {
            var key = e.which || e.keyCode;

            if (!(key >= 48 && key <= 57) && // Interval (0-9)
                 (key !== 8) &&              // Backspace
                 (key !== 9) &&              // Horizontal tab
                 (key !== 37) &&             // Percentage
                 (key !== 39) &&             // Single quotes (')
                 (key !== 46))               // Dot
            {
                e.preventDefault();
                return false;
            }
        });
    }
});

但如果您想使用 ng-repeat 并且您只需要在一定数量的字段中应用此指令。好吧,您可以将upper指令转换为准备接受 true false 值的指令,以便能够确定哪个字段会受其影响。

But what happens if you want to use ng-repeat and you need to apply this directive only in a certain number of fields. Well, you can transform the upper directive into one prepared to admit a true or false value in order to be able to decide which field will be affected by it.

myApp.directive('rsInteger', function() {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            if (attrs.rsInteger === 'true') {
                element.bind('keydown', function(e)
                {
                    var key = e.which || e.keyCode;

                    if (!(key >= 48 && key <= 57) && // Interval (0-9)
                         (key !== 8) &&              // Backspace
                         (key !== 9) &&              // Horizontal tab
                         (key !== 37) &&             // Percentage
                         (key !== 39) &&             // Single quotes (')
                         (key !== 46))               // Dot
                    {
                        e.preventDefault();
                        return false;
                    }
                });
            }
        }
    }
});

要使用这个新指令,你只需要在这样的输入类型文本中进行,例如:

To use this new directive you just need to do it in a input type text like this, for example:

<input type="text" rs-integer="true">

希望对您有帮助。

这篇关于JavaScript - 测试整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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