Validating An Email In A .NET API

This is a short post, but one I felt compelled to write after I saw some absolutely bonkers ways of validating emails in a .NET Core API. I recently stumbled upon a war between two developers who were duking it out on a pull request/code review. It all centred around the “perfect” regex for validating an email.

And you may be thinking, isn’t it use [email protected]? Well.. Apparently not. Just check out this rather verbose stackoverflow answer here on the subject :

The answer given has the regex looking a bit like so :


…not the most concise.

Another example might be if we take a look at how Angular validates email. Also with a Regular Expression found here :

And it looks a bit like so :


A little bit different, but still a pretty massive regex pattern. So, given these options (And probably many many more), which should we copy and paste into our validation for our model?

public class CreateAccountViewModel
public string Email { get; set; }

The answer is none of the above. .NET Core (And .NET Framework) have an inbuilt validator for emails like so :

public class CreateAccountViewModel
public string Email { get; set; }

Nice and simple without much fuss. But the question then is, what Regex does .NET Core/.NET 5+ use out of the box? The answer is.. It doesn’t use regex at all!

The logic is actually rather simple :

Does the value have an @ symbol?
Is the @ symbol in any position but the first or last index of the string

No regex required!

Is this a perfect validator? Probably not, it probably allows through emails that aren’t quite up to spec with the email address RFC, but it does enough to catch the 99.99%. So next time people are arguing over the perfect email regex, maybe the answer is to not use regex at all!

The post Validating An Email In A .NET API appeared first on .NET Core Tutorials.

Flatlogic Admin Templates banner

Leave a Reply

Your email address will not be published. Required fields are marked *