Checking Email Addresses (and Other Text) for Illegal Chars

by Oct 24, 2016

Here is a quick approach to do sanity checks and validate data. Let’s assume you’d like to find out whether an email address contains illegal characters:

# some email address $mail = 'thomas.bö' # list of allowed characters $pattern = '[^a-z0-9.@]' if ($mail -match $pattern) { ('Invalid character in email address: {0}' -f $matches[0]) } else { 'Email address is good.' } 

This piece of code uses a regular expression. The regular expression lists all legal characters (letters a through z, numbers, plus some special characters). By prepending “^”, the list is inverted and now resembles all illegal characters. If at least one is found, the first found illegal character is returned.

 Invalid character in email address: ö 

Twitter This Tip! ReTweet this Tip!