title: Register with unique email OR unique username in ASP.NET Core MVC
body: <p>I am working on a system that should allow users to register by a unique username, or unique email. Register by both is possible as well.</p>
  <p>I am using the default identity pages with some modifications, here is a sample of the register code:</p>
  <pre><code>    public class InputModel
      {
          //[Required] //Validated in server side based on role
          [EmailAddress]
          [Display(Name = &quot;Email&quot;)]
          public string Email { get; set; }
  
          //[Required] //Validated in server side based on role
          [Display(Name = &quot;Username&quot;)]
          public string UserName { get; set; }
  
          [Required]
          [Display(Name = &quot;Name&quot;)]
          public string Name { get; set; }
      }
  
      public async Task&lt;IActionResult&gt; OnPostAsync(string returnUrl = null)
      {
          string username = Input.UserName ?? Input.Email;
  
          if (ModelState.IsValid)
          {
              var user = new ApplicationUser
              {
                  UserName = username,
                  Email = Input.Email,
                  Name = Input.Name,
              };
          }
      }
  </code></pre>
  <p>Basically, if the user entered a username, Username column will be Input.UserName.
  if no username (only email), the Username = Input.Email, because obviously it cannot be empty. Now both username and email are equal as the default.</p>
  <p>examples:</p>
  <p>Username: <strong>a@a</strong> , Email: <strong>a@a</strong>   , &gt;&gt; no username</p>
  <p>Username: <strong>xyz</strong> , Email: <strong>null</strong>  , &gt;&gt; no email</p>
  <p>Username: <strong>abc</strong> , Email: <strong>a@b</strong>  , &gt;&gt; user entered both username and email</p>
  <p>For now, username is always unique and always required (required by identity not the user), but not the case for the email, it can be null as expected but its not unique, I added this line in the startup.cs for the uniqueness:</p>
  <pre><code>            services.AddIdentity&lt;IdentityUser, IdentityRole&gt;(options =&gt; {
              options.User.RequireUniqueEmail = true;
          })
  </code></pre>
  <p>but now it cannot be null, it give this validation error:</p>
  <blockquote>
  <p>Email '' is invalid.</p>
  </blockquote>