Q:

Asp.Net Core Email Field validation in cshtml file

In a a .cshtml file I have the folloeing code :
            <form asp-action="ResetMailAndResendConfirmation">
                <div asp-validation-summary="All" class="text-danger"></div>
                <div class="form-group">
                    <label asp-for="@Model.NewEmail" class="control-label">Nuova Email:</label>
                    <input asp-for="@Model.NewEmail" class="form-control" />
                    <span asp-validation-for="@Model.NewEmail" class="text-danger"></span>
                </div>
                <div class="actions">
                    <button type="submit" class="btn btn-default">Spedisci mail</button>
                </div>
            </form>

What is the shortest and most advanced way to validate the e-mail field? Thanks for your help.

A:

If your property is decorated with either [EmailAddress] or [DataType(DataType.EmailAddress)], then Razor will actually render the input with type="email". You can also manually add this type yourself in the HTML. That gives you very basic validation, basically just that it has an @ sign. However, it's still important to add regardless, as it hints both to the mobile device (if mobile) and any form filling systems, enabling a better experience for the user.
The chief issue here, and the reason why the default validation is just a presence of @ is that email addresses can be quite complex, and there's no easy rules as to what makes a valid one or not. The best you can do is a custom regex, which you can add via the pattern attribute in HTML. The official regex from RFC 5322 is:
\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*
 |  "(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]
      |  \\[\x01-\x09\x0b\x0c\x0e-\x7f])*")
@ (?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?
  |  \[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}
       (?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:
          (?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]
          |  \\[\x01-\x09\x0b\x0c\x0e-\x7f])+)
     \])\z

As you can see: complex. More realistically, you can use the better but still large regex:
\A[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@
(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\z

That covers the largest majority of valid email addresses, and should be fine for most uses. These regex strings and additional information about why email validation is problematic can be found in this excellent article.

