JavaScript - Test for an integer

前端 未结 11 1926
醉梦人生
醉梦人生 2020-12-02 11:17

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

相关标签:
11条回答
  • 2020-12-02 11:28

    function isInt(x) {return Math.floor(x) === x;}

    0 讨论(0)
  • 2020-12-02 11:30

    UPDATE

    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;
    

    Thanks Donald.McLean :)


    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;
        }
    });
    

    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;
                }
            });
        }
    });
    

    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">
    

    Hope it helps you.

    0 讨论(0)
  • 2020-12-02 11:31

    You may use isInteger() method of Number object

    if ( (new Number(x)).isInteger() ) {
      // handle integer
    }
    

    This method works properly if x is undefined or null. But it has poor browser support for now

    0 讨论(0)
  • 2020-12-02 11:32

    I did this to check for number and integer value

    if(isNaN(field_value * 1) || (field_value % 1) != 0 ) not integer;
    else integer;
    

    Modular Divison

    Example
    1. 25.5 % 1 != 0 and ,
    2. 25 % 1 == 0

    And if(field_value * 1) NaN if string eg: 25,34 or abcd etc ... else integer or number

    0 讨论(0)
  • 2020-12-02 11:33

    If your number is in the 32bit integer range, you could go with something like:

    function isInt(x) { return ""+(x|0)==""+x; }
    

    The bitwise or operator forces conversion to signed 32bit int. The string conversion on both sides ensures that true/false want be matched.

    0 讨论(0)
  • 2020-12-02 11:36

    Nobody tried this simple thing?

    function isInt(value) {
        return value == parseInt(value, 10);
    }
    

    What's wrong with that?

    0 讨论(0)
提交回复
热议问题