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 : https://stackoverflow.com/a/201378/177516

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

(?:[a-z0-9!#$%&’*+/=?^_`{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_`{|}~-]+)*|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|\[x01-x09x0bx0cx0e-x7f])*”)@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])).){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|\[x01-x09x0bx0cx0e-x7f])+)])

…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 : https://github.com/angular/angular/blob/master/packages/forms/src/validators.ts#L98

And it looks a bit like so :

^(?=.{1,254}$)(?=.{1,64}@)[a-zA-Z0-9!#$%&’*+/=?^_`{|}~-]+(?:.[a-zA-Z0-9!#$%&’*+/=?^_`{|}~-]+)*@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$

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
{
[RegularExpression(“SoMeCrAzYReGeX”)]
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
{
[EmailAddress]
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 *