Accept User Input with Validator

by Apr 26, 2016

Of course you can use Read-Host to ask a user for some input, or use mandatory parameters. They all are kind of ugly, and have next to no validation. Here is a function that makes things easier:

function Get-UserInput
{

  param
  (
    [Parameter(Mandatory=$true)]
    $Prompt,

    [ScriptBlock]
    $Validator = $null,

    $ErrorMessage = 'Incorrect. Try again!'

  )
  do
  {
    Write-Host "$Prompt " -NoNewline
    Write-Host "[>>>] " -ForegroundColor Yellow -NoNewline
    $userinput = Read-Host

    if ($Validator -ne $null)
    {
      $_ = $userinput
      $ok = & $Validator 
    }
    else
    {
      $ok = $true
    }

    if (!$ok)
    {
      Write-Host $ErrorMessage -ForegroundColor Red
    }
  } until ($ok)

  $userinput
}

Get-UserInput just needs a prompt text, an error text, and a validator. The validator can be any piece of PowerShell code. It checks the user input. Here is a simple example, asking for a birthday:

Get-UserInput -Prompt 'Enter your birthday' -Validator { $_ -as [DateTime] } -ErrorMessage 'Should be a date. Try again!'

And this is the result:

 
Enter your birthday [>>>] won't tell you!
Should be a date. Try  again! 
Enter your birthday [>>>] 1/1/2001
1/1/2001
 

Twitter This Tip! ReTweet this Tip!