How to check if user already exists on client-side in ASP.NET MVC 5?

Deilan picture Deilan · Feb 13, 2015 · Viewed 18.6k times · Source

Using Visual Studio 2013.4 (Visual Studio 2013 Update 4) I have created a regular ASP.NET MVC 5 project with Individual User Accounts authentication configuration. All the users registration and log-in features has been already scaffolded for me by Visual Studio and works fine.

How to implement client-side validation of the following rule on the registration page: There is no already registered user with the same Email?

Answer

Deilan picture Deilan · Feb 13, 2015

You could use RemoteAttribute to perform client side validation with a server callback.

1) Add the following method to the AccountController:

[AllowAnonymous]
public async Task<JsonResult> UserAlreadyExistsAsync(string email)
{
    var result = 
        await userManager.FindByNameAsync(email) ?? 
        await userManager.FindByEmailAsync(email);
    return Json(result == null, JsonRequestBehavior.AllowGet);
}

2) Add Remote attribute to Email property of RegisterViewModel class:

[Remote("UserAlreadyExistsAsync", "Account", ErrorMessage = "User with this Email already exists")]
public string Email { get; set; }

where "Account" is the name of the serving controller and "UserAlreadyExistsAsync" is it's action name.