Skip to content

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

Closed

Description

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.

Activity

  1. powercode commented on Apr 23, 2017

    @powercode
    Collaborator

    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}'")]
    

    It got merged just 3 days ago.

  2. SteveL-MSFT commented on Apr 23, 2017

    @SteveL-MSFT
    Member

    Looks to me like that PR should address this.

  3. mklement0 commented on May 9, 2017

    @mklement0
    ContributorAuthor

    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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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