Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can ensure that a function only accepts a positive integer?

Tags:

int

powershell

I want to do some basic validation on a user input in PowerShell to ensure a user can only enter a whole integer and does not enter -7 for example. I am not sure how this is done and would appreciate a pointer.

[parameter(Mandatory=$false)][int]$number

If a user enters -$number this will be accepted. I want it to reject this type of input.

like image 884
a_m_2016 Avatar asked May 12 '16 13:05

a_m_2016


People also ask

How do you take only positive integer input in python?

The abs() function is used to get the absolute (positive) value of a given number. The argument may be an integer or a floating point number. If the argument is a complex number, its magnitude is returned.

How do you check if a number is a positive integer?

If the Integer is greater than zero then it is a positive integer. If the number is less than zero then it is a negative integer. If the number is equal to zero then it is neither negative nor positive.

How do you define only positive numbers in Python?

Use abs(x) Python native function. EDIT: if you want to raise an error, instead, I would make use of assertions (example taken from here: x = 0 assert x > 0, 'Only positive numbers are allowed' print('x is a positive number.


2 Answers

You can use ValidateRange for the parameter:

[parameter(Mandatory=$false)]
[ValidateRange(1, [int]::MaxValue)]
[int] $number

From the documentation:

ValidateRange Validation Attribute

The ValidateRange attribute specifies a numeric range for each parameter or variable value. Windows PowerShell generates an error if any value is outside that range. In the following example, the value of the Attempts parameter must be between 0 and 10.

Param
(
    [parameter(Mandatory=$true)]
    [ValidateRange(0,10)]
    [Int]
    $Attempts
) 

In the following example, the value of the variable $number must be between 0 and 10.

[Int32][ValidateRange(0,10)]$number = 5
like image 167
Joey Avatar answered Oct 02 '22 14:10

Joey


Since PowerShell 6.1.0 you kan use ValidateRangeKind to initialize the attribute:

[Parameter(Mandatory = $false)]
[ValidateRange("Positive")]
[Int] $Number = 5

ValidateRange validation attribute

The ValidateRange attribute specifies a numeric range or a ValidateRangeKind enum value for each parameter or variable value. PowerShell generates an error if any value is outside that range.

The ValidateRangeKind enum allows for the following values:

  • Positive - A number greater than zero.
  • Negative - A number less than zero.
  • NonPositive - A number less than or equal to zero.
  • NonNegative - A number greater than or equal to zero.
like image 31
mhu Avatar answered Oct 02 '22 13:10

mhu