Development Tip

JavaScript-정수 테스트

yourdevel 2020. 10. 13. 19:28
반응형

JavaScript-정수 테스트


사용자가 나이를 입력 할 수있는 텍스트 필드가 있습니다. JavaScript로이 필드에 대해 클라이언트 측 유효성 검사를 수행하려고합니다. 이미 서버 측 유효성 검사가 있습니다. 그러나 사용자가 실제 정수를 입력했는지 확인할 수없는 것 같습니다. 현재 다음 코드를 시도하고 있습니다.

    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를 반환한다는 것입니다. 사용자가 정수만 입력하도록하려면 어떻게해야합니까?

감사합니다


최신 정보

나는 오류를했고라는 VAR 추가 한 코드 해결 한 키를 저장하는 데 사용 코드를 누르면 keyCode가 하고 있는 브라우저의 따라 달라집니다.

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

감사합니다 Donald. McLean :)


입력하는 동안 숫자를 쓰고 있는지 확인하고 입력 필드에 다른 문자를 쓰지 않도록하려면이 간단한 함수를 사용하고 허용되는 요소를 정의 할 수 있습니다 (필터링하려는 항목 포함). 이런 식으로 정수뿐만 아니라 특정 문자 그룹을 선택할 수 있습니다. 이 예제는 jQuery를 기반으로 입력 필드에 연결합니다.

$('#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가 요즘 강해지고 있기 때문입니다. 웹 앱의 모든 필드에서이 작업을 수행하기 위해 만들 수있는 지시문입니다.

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하고 싶고 특정 수의 필드에만이 지시문을 적용해야하는 경우 어떻게됩니까 ? 음, 어떤 필드가 영향을 받을지 결정할 수 있도록 상위 지시문을 또는 거짓을 승인 할 준비가 된 것으로 변환 할 수 있습니다 .

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

이 새 지시문을 사용하려면 다음과 같은 입력 유형 텍스트에서 수행하면됩니다.

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

도움이 되었기를 바랍니다.


var intRegex = /^\d+$/;
if(intRegex.test(someNumber)) {
   alert('I am an int');
   ...
}

사용자가 음이 아닌 정수가 아닌 다른 것을 입력하면 절대적으로 실패합니다.


실제 정수 검사의 경우 다음을 사용하십시오.

function isInt(value) { 
    return !isNaN(parseInt(value,10)) && (parseFloat(value,10) == parseInt(value,10)); 
}

많은 int 검사의 문제는 유효한 정수인 1.0에 대해 'false'를 반환한다는 것입니다. 이 메서드는 float 및 int 구문 분석의 값이 동일한 지 확인하므로 # .00의 경우 true를 반환합니다.

최신 정보:

Two issues have been discussed in the comments I'll add to the answer for future readers:

  • First, when parsing string values that use a comma to indicate the decimal place, this method doesn't work. (Not surprising, how could it? Given "1,001" for example in the US it's an integer while in Germany it isn't.)
  • Second, the behavior of parseFloat and parseInt has changed in certain browsers since this answer was written and vary by browser. ParseInt is more aggressive and will discard letters appearing in a string. This is great for getting a number but not so good for validation.

My recommendation and practice to use a library like Globalize.js to parse numeric values for/from the UI rather than the browser implementation and to use the native calls only for known "programmatically" provided values, such as a string parsed from an XML document.


use isNaN(n)

i.e.

if(isNaN(intValue))

in place of

if (intValue == Number.NaN)

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


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


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.


Nobody tried this simple thing?

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

What's wrong with that?


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


I found the NaN responses lacking because they don't pick up on trailing characters (so "123abc" is considered a valid number) so I tried converting the string to an integer and back to a string, and ensuring it matched the original after conversion:

if ("" + parseInt(stringVal, 10) == stringVal) { alert("is valid number"); }

This worked for me, up until the numbers were so large they started appearing as scientific notation during the conversion.

...so of course this means you could enter a number in scientific notation, but checking minimum and maximum values as well would prevent that if you so desire.

It will of course fail if you use separators (like "1,000" or "1.000" depending on your locale) - digits only allowed here.


If (enteredAge < "1" || enteredAge > "130") ......

Simple and it works....until they develop immortality

참고URL : https://stackoverflow.com/questions/1019515/javascript-test-for-an-integer

반응형