Deny user to input string with two dots

This topic contains 6 replies, has 4 voices, and was last updated by  Peter Jurgens 1 week, 1 day ago.

  • Author
    Posts
  • #77086

    Vandrey Trindade
    Participant

    Hi,

    I want to deny a variable that has two, or more, dots on a string.

    This are allowed values:

    40.1 , 45.26, 220.243

    This shouldnt' be allowed:

    40.1. , 45..26, .220.243, 192.168.44.2

    I hate myself for not knowing regex...

  • #77091

    Vandrey Trindade
    Participant

    Certainly not the best way, but I did it using this:

    if ($IP.Split(".").Count -gt 2){"Error"}
  • #77100

    David Flores
    Participant

    I'm not a Regex guy either, but here's my best effort:

    [PS] C:\temp>$a = "40.1"
    [PS] C:\temp>$a -match ("^[\d]{1,3}\.[\d]{1,3}$")
    True
    [PS] C:\temp>$a = "45.26"
    [PS] C:\temp>$a -match ("^[\d]{1,3}\.[\d]{1,3}$")
    True
    [PS] C:\temp>$a = "40.1."
    [PS] C:\temp>$a -match ("^[\d]{1,3}\.[\d]{1,3}$")
    False
    [PS] C:\temp>$a = "45..26"
    [PS] C:\temp>$a -match ("^[\d]{1,3}\.[\d]{1,3}$")
    False
    [PS] C:\temp>$a = ".220.243"
    [PS] C:\temp>$a -match ("^[\d]{1,3}\.[\d]{1,3}$")
    False
    [PS] C:\temp>$a = "192.168.44.2"
    [PS] C:\temp>$a -match ("^[\d]{1,3}\.[\d]{1,3}$")
    False

    Keep in mind that this regex doesn't limit your decimal values to between 0-255, which you may or may not want.

    • #77151

      Vandrey Trindade
      Participant

      David Flores,

      Thanks! I managed the 0-255 in another way. =]

  • #77118

    Mike
    Participant

    This seems to work:

    $thing -notmatch ".*\..*\..*"

    Admittedly I tried solving it myself and ended up googling it.

    I learnt regex a while back but have forgotten most of it. I recall these were very good resources:

    -regex buddy (free trials available)
    -Sams Teach Yourself Regular Expressions in 10 Minutes

    • #77128

      David Flores
      Participant

      The SAMS book is what I use. Highly recommended. No, you wont teach yourself regex in 10 minutes, but it's about as painless an introduction to the subject as I've found. A mastery of Regex is one those skills that separates the men from the boys, IMHO (I count myself as still very much among the boys).

  • #77164

    Peter Jurgens
    Participant

    Here's the solution I came up with using ValidateScript. Note that ValidateScript is not explicitly for parameter validation and can be used anywhere in your scripts if you wish to validate assignment of values to variables etc.

    [validatescript({[regex]::matches($_,"\.").count -le 1})]$var = "4.1"
    

    Above works but below doesn't:

    [validatescript({[regex]::matches($_,"\.").count -le 1})]$var = "192.168.."
    

You must be logged in to reply to this topic.