You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The Validate* parameter attributes are a wonderful way of enforcing constraints on arguments (parameter values) that go beyond type checking.
Unfortunately, the generic error messages that result when validation fails are often not helpful enough, and inherently they cannot always be.
Therefore, it would be great if a custom error message could be provided as part of the attribute declaration.
Consider this case:
> function foo { param([ValidateScript({ $_-match'^\p{L}\d+' })] $bar) }; foo -bar baz
foo : Cannot validate argument on parameter 'bar'. The "$_ -match '^\p{L}\d+' " validation script for the argument with value "baz" did not return a result of True.
# ...
The error message is noisy and unhelpful, and, in the absence of additional information, cannot be more helpful.
A workaround is to have an explicit Throw statement in the script block, but that's clumsy and cumbersome.
It would be nice to do something like this instead:
> function foo { param([ValidateScript({ $_-match'^\p{L}\d+' },'You must specify a letter followed by one or more digits.')] $bar) }; foo -bar baz
foo : Cannot validate argument on parameter 'bar'. You must specify a letter followed by one or more digits.
# ...
Additional considerations:
Support placeholders such as {0} in the message that can access the argument passed as well as the (other) arguments passed to the validation attribute constructor.
(This is already used internally for the generic error messages.)
Both ValidateScript and ValidatePattern implements an ErrorMessage property. See #2728.
[ValidateScript("$_ % 2", ErrorMessage = "The item '{0}' did not pass validation of script '{1}'")]
[ValidatePattern("\s+", ErrorMessage="The text '{0}' did not pass validation of regex '{1}'")]
Activity
powercode commentedon Apr 23, 2017
Both ValidateScript and ValidatePattern implements an ErrorMessage property. See #2728.
It got merged just 3 days ago.
SteveL-MSFT commentedon Apr 23, 2017
Looks to me like that PR should address this.
mklement0 commentedon May 9, 2017
Thanks, guys, I wasn't aware of that.
It's a great step in the right direction, but I think it should be implemented for all validation attributes: see #3745