Author Posts

April 19, 2018 at 8:40 pm

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

April 19, 2018 at 8:50 pm

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

http://emailregex.com/

April 19, 2018 at 11:35 pm

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

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

April 20, 2018 at 6:07 am

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

April 20, 2018 at 11:58 am

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

April 20, 2018 at 8:50 pm

Thanks for this guys, amazing whats out on the net 😉

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