Being Able To Login Using UserName or Email address in ASP.NET Core MVC

I want user to be able to login using UserName or Email in ASP.NET Core MVC. In case of using the [Required] attribute, both the UserName and the Email must be entered in the model properties during login. While doing the form validation on the server-side, I need to perform model validation before accessing the data access layer in the application where the N-Tier architecture is implemented.

namespace LoginApplication.WebUI.Models
{
    public class LoginModel
    {
        /// <summary>Which data annotation attribute should I use?</summary>
        public string UserName { get; set; }

        /// <summary>Which data annotation attribute should I use?</summary>
        public string Email { get; set; }

        [Required]
        [DataType(DataType.Password)]
        public string Password { get; set; }
    }
}

namespace LoginApplication.WebUI.Controllers
{
    public class AccountController : Controller
    {
        /* Other LOCs: Dependency Injection, "Login" Action HttpGet Method */

        [HttpPost]
        public async Task<IActionResult> Login(LoginModel model)
        {
            /* At this stage I need to validate the model correctly. */
            if(ModelState.IsValid)
            {
                /* Other LOCs: User Query, Password Authentication, Page Redirection
                               Error Message Management, Log Management */
            }
            return View(model);
        }
    }
}

In this case, what attribute should I use defined in the System.ComponentModel.DataAnnotations namespace? Or is there another way to work around this situation?


You need to implement a custom validator. When you implement a Custom Validator, you can decide the logic and it can be implemented in both server-side and client-side. And ASP.NET validation infrastructure takes care of validating it along with the other validators.

Here is the doc which talks about implementing custom validation

Here is one example - https://stackoverflow.com/a/15975880/38024 which will help you. Or you can use external nuget packages like ExpressiveAnnotations