Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Read-Variable field validation
<#
.SYNOPSIS
Prompts user for 3 values and validates them in 3 different ways, then outputs them to the Host.
.DESCRIPTION
Example scripts that prompts user for 3 values and validates them in 3 different ways, then outputs them to the Host.
$userName uses simplest "Mandatory" validator that only checks that string is not empty - this validator works only on some fields.
$password is validated in the global validator at the end of the command.
$description is validated by a local parameter "Validator" script block that only checks a single entry
.NOTES
Adam Najmanowicz - https://gist.github.com/AdamNaj/37ad58e1a9350604e4815ca586acf39e
#>
$result = Read-Variable -Parameters `
@{ Name = "userName"; Value=""; Title="UserName"; Placeholder="User name goes here"; Mandatory=$true},
@{ Name = "password"; Value=""; Title="Password"; Editor="password"; Placeholder="Password goes here"},
@{ Name = "description"; Value=""; Title="Description"; Lines=3; Placeholder="User description"; Validator={
if([string]::IsNullOrEmpty($variable.Value)){
$variable.Error = "Please provide a description."
}}} `
-Description "This Dialog shows how to provide a validator for values" `
-Title "Password entry" -Width 450 -Height 410 -OkButtonName "Proceed" -CancelButtonName "Abort" -ShowHints `
-Validator {
$minPassLength = 6
$pass = $variables.password.Value;
if($pass.Length -ge $minPassLength)
{
$valErr = @()
if (-not ($pass -match "[^a-zA-Z0-9]")) #check for special chars
{
$valErr += "special character"
}
if (-not ($pass -match "[0-9]"))
{
$valErr += "number"
}
if (-not ($pass -cmatch "[a-z]"))
{
$valErr += "lowercase character"
}
if (-not ($pass -cmatch "[A-Z]"))
{
$valErr += "uppercase character"
}
if($valErr.Count -gt 0){
$variables.password.Error = "Password must have at least one: " + ( $valErr -Join ", ")
}
}
else
{
$variables.password.Error = "Password must be at least " + $minPassLength + " characters long"
}
}
$userName
$password
$description
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment