Validating User Input

by Jan 23, 2009

When writing a function that accepts parameters, you can strongly-type parameters so that an exception occurs when the user submits the wrong parameters:

function Get-Days {
param( [DateTime] $date )
[Int] (New-TimeSpan $date (Get-Date)).TotalDays
}
Get-Days '1.1.1980'
Get-Days 'Hello' # raises an exception

This common approach has two problems:

  1. You may want to handle the exception inside of your function
  2. You may want to convert the user input using a non-standard conversion. For example, the user-supplied date was converted using the en-US culture in the previous example and may be off if you specify dates in another culture format.

To solve the problem, validate the input:

function Get-Days {
param( $date )
if (!($date -as [DateTime])) {
'You did not specify a date!'
return
}
$date = [DateTime]::Parse($date)
[Int] (New-TimeSpan $date (Get-Date)).TotalDays
}
Get-Days '1.1.1980'
Get-Days "Hello"
Get-Days '1.1.1980'

When you validate user input yourself, use -as to check whether user input can be converted to a specific type. Use the static parse () method provided by the DateTime type to convert user input to a DateTime using the current culture. Use return to exit a function early.