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
The most elegant way is to use .Net's built in methods.
These methods:
Are tried and tested. These methods are used in my own professional projects.
Use regular expressions internally, which are reliable and fast.
Made by Microsoft for C#. There's no need to reinvent the wheel.
Return a bool result. True means the email is valid.
For users of .Net 4.5 and greater
Add this Reference to your project:
Now you can use the following code:
Example of use
Here are some methods to declare:
...and code demonstrating them in action:
In addition, this example:
;
.Alternative, for users of a version of .Net less than 4.5
For situations where .Net 4.5 is not available, I use the following solution:
Specifically, I use:
I wrote an function to check if an email is valid or not. It seems working well for me in most cases.
Results:
Code:
a little modification to @Cogwheel answer
Here is an answer to your question for you to check.
What about this?
To clarify, the question is asking whether a particular string is a valid representation of an e-mail address, not whether an e-mail address is a valid destination to send a message. For that, the only real way is to send a message to confirm.
Note that e-mail addresses are more forgiving than you might first assume. These are all perfectly valid forms:
For most use cases, a false "invalid" is much worse for your users and future proofing than a false "valid". Here's an article that used to be the accepted answer to this question (that answer has since been deleted). It has a lot more detail and some other ideas of how to solve the problem.
Providing sanity checks is still a good idea for user experience. Assuming the e-mail address is valid, you could look for known top-level domains, check the domain for an MX record, check for spelling errors from common domain names (gmail.cmo), etc. Then present a warning giving the user a chance to say "yes, my mail server really does allow
In case you are using FluentValidation you could write something as simple as this: