What is the most elegant code to validate that a string is a valid email address?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
There are a lot of strong answers here. However, I recommend that we take a step back. @Cogwheel answers the question https://stackoverflow.com/a/1374644/388267. Nevertheless, it could be costly in a bulk validation scenario, if many of the email address being validated are invalid. I suggest that we employ a bit of logic before we enter into his try-catch block. I know that the following code could be written using RegEx but that could be costly for new developers to understand. This is my twopence worth:
I use this single liner method which does the work for me-
As per the comments, this will "fail" if the
source
(the email address) is null.I find this regex to be a good trade off between checking for something more than just the @ mark, and accepting weird edge cases:
It will at least make you put something around the @ mark, and put at least a normal looking domain.
The most voted answer from @Cogwheel is best answer however i have tried to implement
trim()
string method so it will trim all user white space from string start to end. Check the code bellow for full example-Simple way to identify the emailid is valid or not.
There is culture problem in regex in C# rather then js. So we need to use regex in US mode for email check. If you don't use ECMAScript mode, your language special characters are imply in A-Z with regex.