Skip to content

Suggestion: Implement optional custom error messages for validation parameter attributes #3630

@mklement0

Description

@mklement0

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.)

  • Provide a mechanism to localize the messages.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions