[SalesForce] Check For Special Characters in Emails

I'm having a business requirement of searching special characters in Email Field(before @domain.com)in a trigger.

For Ex: if a email is like this (t#@est@gmail.com).it should be able to identify the'#@' and make that email field blank.Is there any way available to identify the special characters before '@gmail.com'.

Best Answer

Use String.containsNone() to check whether a string contains any prohibited characters, or String.containsOnly() to check that it only contains a specific set of characters. That said, be aware that email addresses are a good deal more flexible than you might think, and special characters aren't necessarily invalid.

Regular expressions are generally not a good fit for validating email addresses, which is surprisingly tricky. There's a lot of edge cases that are perfectly valid but that your regex in the comments will not match. Your regex, for example, won't match john.smith+stuff@gmail.com, which is not only valid but common, or webmaster@company.cloud. (There are now a lot of TLDs, not all of which are 2-4 characters long).

For more on why parsing and validating email addresses is really hard, and most validation is too strict or just plain wrong, see for example this article, or read the relevant RFCs 822, 2821, 2822, 3696.

Related Topic