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?
UserName,Email,Password) are available in the Login.cshtml file in the View layer of MVC.Passwordwill be a required field. Only one of theUserNameorEmailinformation will be mandatory. What I want to ask here is an "OR" relationship where one of the two fields (UserName,Email) will be accepted but the preference will be determined by the user at login.