Skip to content

Parameters to methods in classes should be able to take [VALIDATExxx] attributes. #2485

@jpsnover

Description

@jpsnover

Should be able to add validate attributes to params like:

class NetHelper
{
   static [String]ConvertToSubnetMask(
           [ValidateRange(0, 32)]
           [UInt32]$PrefixLength
   )
   {
       $byteMask = ([Convert]::ToUInt32($(("1" \* $PrefixLength).PadRight(32, "0")), 2))
       $bytes = [BitConverter]::GetBytes($byteMask)
       [Array]::Reverse($bytes)
       $ipAddress = New-Object System.Net.IPAddress -ArgumentList (, $bytes)
       return $ipAddress.IPAddressToString
   }
}

Just to be clear - I understand that we are creating a proper .net class and using real .Net call conventions.
What I'm suggesting is that underneath the covers, we implement something along the lines of:

class NetHelper
{
  static [String]ConvertToSubnetMask(
          [UInt32]$PrefixLength
  )
  {
      [ValidateRange(0, 32)]$LocalPrefixLength = $PrefixLength
      $byteMask = ([Convert]::ToUInt32($(("1" \* $LocalPrefixLength).PadRight(32, "0")), 2))
      $bytes = [BitConverter]::GetBytes($byteMask)
      [Array]::Reverse($bytes)
      $ipAddress = New-Object System.Net.IPAddress -ArgumentList (, $bytes)
      return $ipAddress.IPAddressToString
  }
}

Error message example:

The attribute cannot be added because variable LocalPrefixLength with value 35 would no longer be valid.
At line:8 char:8
-        [ValidateRange(0, 32)]$LocalPrefixLength = $PrefixLength
-        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  - CategoryInfo          : MetadataError: (:) [], ValidationMetadataException
  - FullyQualifiedErrorId : ValidateSetFailure (edited)
> $PSVersionTable


Name                           Value
----                           -----
PSVersion                      5.1.14393.206
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.14393.206
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1

Metadata

Metadata

Assignees

No one assigned

    Labels

    KeepOpenThe bot will ignore these and not auto-closeUp-for-GrabsUp-for-grabs issues are not high priorities, and may be opportunities for external contributorsWG-Enginecore PowerShell engine, interpreter, and runtime

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions