bish
bish

Reputation: 3419

Validating a string as a positive integer

I'm trying to solve a quite common problem - validating the input to be a positive integer greater 1. What I've tried so far works as long as the input is not in science notation.

I searched quite long on SO for solution but didn't find any for this specific case. So this is my current code:

If IsNumeric(objArgs(1)) Then

  If CLng(objArgs(1)) = objArgs(1) Then
    if(objArgs(1) < 1) then
      wscript.echo "2nd parameter must be greater than 1"
    else
      ' move on
    end if
  else
    wscript.echo "2nd parameter is not an integer"
  end if
  else
    wscript.echo "2nd parameter is not numeric"      
end if

This works fine when the input is something like a, 0, -10, 3.14 and so on.

My problem occures when I enter a (large) number in science notation, like 1E+48. If I enter this I get a overflow-error on the CLng()-function.

How can I avoid this?

Upvotes: 1

Views: 139

Answers (2)

Tomalak
Tomalak

Reputation: 338208

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.

Upvotes: 1

Fabrice NEYRET
Fabrice NEYRET

Reputation: 734

CLng is to convert into longs, which max value is 2^31-1. If you want to test really big number and/or fractionnal numbers, use CDbl (convert into doubles).

Or do you really want to refer to the non-standard class of really big but still integer ? (i.e. integers > 2^31-1).

Upvotes: 0

Related Questions