PowerShell Input Validation with Field-Level Errors
PowerShell
function Test-InputRecord {
param([Parameter(Mandatory)][hashtable]$Record)
$errors = [ordered]@{}
if ([string]::IsNullOrWhiteSpace($Record.email) -or $Record.email -notmatch '^[^@\s]+@[^@\s]+\.[^@\s]+$') {
$errors.email = 'A valid email address is required.'
}
if ($Record.age -notmatch '^\d{1,3}$' -or [int]$Record.age -lt 18) {
$errors.age = 'Age must be an integer of 18 or more.'
}
if ([string]$Record.name -and $Record.name.Length -gt 80) {
$errors.name = 'Name must be 80 characters or fewer.'
}
[pscustomobject]@{ IsValid = $errors.Count -eq 0; Errors = $errors }
}