Deny user to input string with two dots

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…

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

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

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.

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

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

David Flores,

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

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