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
I think the best way is as follow:
You can have this static function in a general class.
Personally, I would say that you should just make sure there is an @ symbol in there, with possibly a . character. There's many regexes you could use of varying correctness, but I think most of these leave out valid email addresses, or let invalid ones through. If people want to put in a fake email address, they will put in a fake one. If you need to verify that the email address is legit, and that the person is in control of that email address, then you will need to send them an email with a special coded link so they can verify that it indeed is a real address.
Here's my answer -- Phil's solution fails for single letter domains like "someone@q.com". Believe it or not, that's used =) (goes to centurylink, for instance).
Phil's answer is also going to work only with PCRE standard... so C# will take it, but javascript is going to bomb. It's too complex for javascript. So you can't use Phil's solution for mvc validation attributes.
Here's my regex. It'll work nicely with MVC validation attributes.
- Everything before the @ is simplified, so that at least javascript will work. I'm okay relaxing validation here as long as exchange server doesn't give me a 5.1.3. - Everything after the @ is Phil's solution modified for single letter domains.
For people suggesting using system.net.mail MailMessage(), that thing is WAY to flexible. Sure, C# will accept the email, but then exchange server will bomb with 5.1.3 runtime error as soon as you try to send the email.
This is an old question, but all the answers I've found on SO, including more recent ones, are answered similarly to this one. However, in .Net 4.5 / MVC 4 you can add email address validation to a form by adding the [EmailAddress] annotation from System.ComponentModel.DataAnnotations, so I was wondering why I couldn't just use the built-in functionality from .Net in general.
This seems to work, and seems to me to be fairly elegant:
.net 4.5 added System.ComponentModel.DataAnnotations.EmailAddressAttribute
You can browse the EmailAddressAttribute's source, this is the Regex it uses internally:
Short and accurate code