Validate That a String Is a Positive Integer

Validate that a string is a positive integer

Two answers for you:

  • Based on parsing

  • Regular expression

Note that in both cases, I've interpreted "positive integer" to include 0, even though 0 is not positive. I include notes if you want to disallow 0.

Based on Parsing

If you want it to be a normalized decimal integer string over a reasonable range of values, you can do this:

function isInDesiredForm(str) {
var n = Math.floor(Number(str));
return n !== Infinity && String(n) === str && n >= 0;
}

or if you want to allow whitespace and leading zeros:

function isInDesiredForm(str) {
str = str.trim();
if (!str) {
return false;
}
str = str.replace(/^0+/, "") || "0";
var n = Math.floor(Number(str));
return n !== Infinity && String(n) === str && n >= 0;
}

Live testbed (without handling leading zeros or whitespace):

function isInDesiredForm(str) {
var n = Math.floor(Number(str));
return n !== Infinity && String(n) === str && n >= 0;
}
function gid(id) {
return document.getElementById(id);
}
function test(str, expect) {
var result = isInDesiredForm(str);
console.log(
str + ": " +
(result ? "Yes" : "No") +
(expect === undefined ? "" : !!expect === !!result ? " <= OK" : " <= ERROR ***")
);
}
gid("btn").addEventListener(
"click",
function() {
test(gid("text").value);
},
false
);
test("1", true);
test("1.23", false);
test("1234567890123", true);
test("1234567890123.1", false);
test("0123", false); // false because we don't handle leading 0s
test(" 123 ", false); // false because we don't handle whitespace
<label>
String:
<input id="text" type="text" value="">
<label>
<input id="btn" type="button" value="Check">

How to check if a string is a positive integer not starting with 0 using regex?

From reading your code it looks like you need to check if a number is grater > 0.

You can do this with this regex:

^[1-9]\d*$

It will check that input:

- starts with a digit but not 0

- contains any number of digits

- does end with a digit

how can I check if a string is a positive integer?

int x;
if (int.TryParse(str, out x) && x > 0)

How to check if a string is a positive integer, allowing 0 and all-0 decimals

First of all the function should be called isNormalNumber instead of isNormalInteger as it accepts decimals, then this is the REgex you need:

    function isNormalNumber(str) {      return /^\+*[0-9]\d*(\.0+)?$/.test(str);    }
alert(isNormalNumber("+10.0") + "::" + isNormalNumber("+10.9") + "::" + isNormalNumber("10"));

Validating a string as a positive integer

validating the input to be a positive integer greater 1

Validation tasks like this one are the domain of regular expressions.

Function IsPositiveInteger(input)
Dim re : Set re = New RegExp

re.pattern = "^\s*0*[1-9]\d*\s*$"
IsPositiveInteger = re.test(input)
End Function

Usage:

MsgBox IsPositiveInteger("asdf")   ' False
MsgBox IsPositiveInteger("0000") ' False
MsgBox IsPositiveInteger("0001") ' True
MsgBox IsPositiveInteger("9999") ' True

Expession

^       # start of string
\s* # allow any number of leading spaces
0* # allow any number of leading zeros
[1-9] # require one digit between 1 and 9
\d* # allow any number of following digits
\s* # allow any number of trailing spaces
$ # end of string

This will recognize any string that qualifies as a positive integer. It will not allow you to see whether the integer that the string represents would fit into one of VBScript's numeric data types.

If such a conversion is necessary for your script then you must apply a range check yourself. This is easily done by lexicographical string comparison.

For a more strict result, remove the parts of the expression that allow leading/trailing spaces.

Test to see if input is a positive integer

Try it this way:

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int value = -1;
do {
System.out.print("Input: ");
String input = scanner.next();
try {
value = Integer.parseInt(input);
} catch (NumberFormatException e) {
System.out.println("Error, try again: " + input);
}
} while (value < 1);
System.out.println(value + " is a positive integer.");
}

How to test if string is 0 or positive integer in JavaScript?

That expression says

  • 0, or
  • 1-9 followed by 0 or more 0-9

Here's a visualization: Link.

so yes, that should cover all non-negative integers. Whether or not regular expressions is the right tool for the job is debatable.

Check if an input string is a positive int/float number

You just need to use !isNaN(s)along with Number(s)>0:

function isPositiveFloat(s) {
return !isNaN(s) && Number(s) > 0;
}

Demo:

function isPositiveFloat(s) {  return !isNaN(s) && Number(s) > 0;}
<input type="text" onchange="console.log(isPositiveFloat(this.value))" />

Check if variable is a number and positive integer in PHP?

To check if a string input is a positive integer, i always use the function ctype_digit. This is much easier to understand and faster than a regular expression.

if (isset($_GET['p']) && ctype_digit($_GET['p']))
{
// the get input contains a positive number and is safe
}


Related Topics



Leave a reply



Submit