Param validate set email address

Hi,

I have a function which has a number of required params, 1 of which is for a email address.

I’m struggling to create a validate set in email format.

Im finding it hard cause i need to cover “@name.co.uk”, “@name.com”, “@name.org” etc. and any format for the first part.

So i need it to say “must be something@something.something”

And clues?

Thanks

Tommy

A lot of smart people already solved these kind of tasks long time ago. No need to re-invent the wheel again and again … :wink: :smiley:

http://emailregex.com/

And with that, you can also use the more appropriate ValidatePattern:

param(
    [Parameter()]
    [ValidatePattern("regexstring")]
    [string]
    $EmailAddress
)

… and with some more research you would find something like this what’s even cooler

function IsValidEmail {
param([string]$EmailAddress)
try {
$null = [mailaddress]$EmailAddress
return $true
}
catch {
return $false
}
}

It’s been found here:
https://stackoverflow.com/questions/48253743/powershell-to-validate-email-addresses?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa

Oh, if there’s a data type designed for it, I’d just [ValidateNotNull()] and have that be the parameter type. No need to mess with complex validations at that point.

param(
    [Parameter()]
    [ValidateNotNull()]
    [mailaddress]
    $EmailAddress
)

Though, depending on your purposes there may be positives and negatives to either approach. :slight_smile:

Thanks for this guys, amazing whats out on the net :wink:

So anyway i’ve added the regex for validate pattern which works perfectly, but can how can i get the error message to say it needs to be in email format rather than

The argument “name” does not match the “^\w+([-+.’]\w+)@\w+([-.]\w+).\w+([-.]\w+)*$” pattern

Thanks

Tom