简体   繁体   中英

How to customize error message returning from UserManager?

I'm developing an application using .Net MVC and Identity. I'm creating new users like this:

result = await UserManager.CreateAsync(user, model.Password);

When e-mail address is already in use, i'm getting an error message. I want to customize that error message.

My Email property in RegisterModel is looking like this:

[Required(ErrorMessage = "Email adresinizi girmediniz.")]
[DataType(DataType.EmailAddress)]
[EmailAddress(ErrorMessage = "Email adresi hatalı.")]
[Display(Name = "Email")]
public string Email { get; set; }

How can i customize that "Email xxx already in use" message?

In the POST method, add a ModelState error for the property and return the view.

if(EmailNotAvailable)
{
  ModelState.AddModelError("Email", "Your custom error message");
  return View(model);
}

You can also use a [Remote] attribute to perform this validation on the client.

[Remote("IsEmailAvailable", "YourControllerName", ErrorMessage = "Your custom error message")]
public string Email { get; set; }

and implement a controller method that checks if the email is avaliable

public JsonResult IsEmailAvailable(string Email)
{
  if(EmailNotAvailable)
  {
    return Json(false, JsonRequestBehavior.AllowGet);
    // or to override the error message you defined in the RemoteAttribute
    return Json("Another custom message, JsonRequestBehavior.AllowGet);
  }
  else
  {
    return Json(true, JsonRequestBehavior.AllowGet);
  }
}

Refer this article for more details on implementing RemoteAttribute

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM