In order not to duplicate the email and username in the database, instead of the any command in SQL, I used is unique in the index section. Now, if a duplicate is entered, it throws an InnerException error. Now, how do I display this error to the user for both the email and the username?
`
public bool IsExistUserName(string userName)
{
return _context.Users.Any(u => u.UserName == userName);
}
public bool IsExistEmail(string email)
{
return _context.Users.Any(u => u.Email == email);
}
//
public IActionResult Register(RegisterViewModel register)
{
if (!ModelState.IsValid)
{
return View(register);
}
if (_userService.IsExistUserName(register.UserName))
{
ModelState.AddModelError("UserName", "You have already registered with this username");
return View(register);
}
if (_userService.IsExistEmail(register.Email.Trim().ToLower()))
{
ModelState.AddModelError("Email", "You have already registered with this email");
return View(register);
}
User user = new User
{
UserName = register.UserName,
Email = register.Email.Trim().ToLower(),
Password = HashPassword.EncodePasswordMd5(register.Password),
ActiveCode = Guid.NewGuid().ToString().Replace("-", ""),
IsActive = false,
RegisterDate = DateTime.Now,
};
_userService.AddUser(user);
return View("SuccsesRegister", user);
}
`
Output: