admin管理员组文章数量:1188003
How can i check is a text entered in a textbox is an integer or not? I used the NAN function but it accepts decimal values too.
How can I do this? Is there any built-in method?
How can i check is a text entered in a textbox is an integer or not? I used the NAN function but it accepts decimal values too.
How can I do this? Is there any built-in method?
Share Improve this question edited Jun 4, 2013 at 17:36 Sled 18.9k27 gold badges124 silver badges172 bronze badges asked Dec 28, 2010 at 6:38 akshayakshay 7555 gold badges16 silver badges22 bronze badges 1- Just noting that Number.isInteger was added in ECMA-262 ed 6 aka ECMAScript 2015. – RobG Commented Mar 25, 2017 at 12:56
7 Answers
Reset to default 17Let's say the text field is referenced by the variable intfield
, then you can check it like this:
var value = Number(intfield.value);
if (Math.floor(value) == value) {
// value is an integer, do something based on that
} else {
// value is not an integer, show some validation error
}
Regular expressions would be a way:
var re = /^-?\d\d*$/
alert(re.test(strNumber)); // leading or trailing spaces are also invalid here
Complete example with updates:
http://rgagnon.com/jsdetails/js-0063.html
function validateInteger( strValue ) {
/************************************************
DESCRIPTION: Validates that a string contains only
valid integer number.
PARAMETERS:
strValue - String to be tested for validity
RETURNS:
True if valid, otherwise false.
**************************************************/
var objRegExp = /(^-?\d\d*$)/;
//check for integer characters
return objRegExp.test(strValue);
}
Updated to handle whitespace - which possibly is not allowed in the validation but here it is anyway: Possible to continue to use the code from the link I gave (leftTrim/rightTrim) but here I reuse trim from .trim() in JavaScript not working in IE
function ignoreLeadingAndtrailingWhitespace( strValue ) {
return strValue.length>0?validateInteger( strValue.trim() ):false;
}
if(typeof String.prototype.trim !== 'function') {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
}
}
function validateInteger( strValue ) {
/************************************************
DESCRIPTION: Validates that a string contains only
valid integer number.
PARAMETERS:
strValue - String to be tested for validity
RETURNS:
True if valid, otherwise false.
**************************************************/
var objRegExp = /(^-?\d\d*$)/;
//check for integer characters
return objRegExp.test(strValue);
}
// validate if the input is numeric and between min and max digits
function validateNumberSize(inputtxt, min, max)
{
var numbers = /^[0-9]+$/;
if(inputtxt.match(numbers))
{
if(inputtxt.length >= min && inputtxt.length <= max)
{
return true;
}
}
return false;
}
var num = document.getElementById("myField").value;
if(/^\d+$/.test(num)) {
// is an int
}
Form data is always text. My suggestion is that you parse it as integer and compare it with the original:
var sampleData = ["not a number", "0", "10", "3.14", "-12", "-0.34", "2e10", "34foo", "foo34"];
var integers = [], notIntegers = [];
for(var i=0, len=sampleData.length; i<len; i++){
var original = sampleData[i];
var parsed = parseInt(original, 10);
if( !isNaN(parsed) && original==parsed ){
integers.push(parsed);
}else{
notIntegers.push(original);
}
}
alert("Integers: " + integers.join(", ") + "\nNot integers: " + notIntegers.join(", "));
This shows:
Integers: 0, 10, -12
Not integers: not a number, 3.14, -0.34, 2e10, 34foo, foo34
Scientific notation is not supported, neither thousand separators. If it's an issue, you need something different ;)
Update: I want to make clear that this is only one of the possible approaches, not the one and only Truth. This approach makes sense if you need to do math with the data so you have to get a numeric variable anyway.
If you are looking either for integer or decimal you can go for:
function IsNumeric(input)
{
return (input - 0) == input && input.length > 0;
}
Best to use the regular expression as follows:
function isInteger(str) {
var r = /^-?[0-9]*[1-9][0-9]*$/;
return r.test(str);
}
Just a test demo:
> function isInteger(str) {
... var r = /^-?[0-9]*[1-9][0-9]*$/;
... return r.test(str);
... }
> isInteger("-123")
true
> isInteger("a123")
false
> isInteger("123.4")
false
本文标签: validationchecking if value of a textfield is integer in javascriptStack Overflow
版权声明:本文标题:validation - checking if value of a textfield is integer in javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738388795a2084322.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论