Param validate set email address

This topic contains 5 replies, has 3 voices, and was last updated by  TommyQuality 1 month ago.

  • Author
    Posts
  • #99273

    TommyQuality
    Participant

    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

  • #99276

    Olaf Soyk
    Participant

    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/

  • #99298

    Joel Sallow
    Participant

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

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

    Olaf Soyk
    Participant

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

  • #99315

    Joel Sallow
    Participant

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

  • #99378

    TommyQuality
    Participant

    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

You must be logged in to reply to this topic.