Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 418
Deilan Avatar asked Feb 13 '15 17:02

Deilan


People also ask

How can check email ID exist or not in ASP NET MVC?

Email = obj. Email; to check if the email exists in db or not; if not exists so it will be added. var exists = db. User.

What is the use of ModelState in MVC?

The ModelState has two purposes: to store and submit POSTed name-value pairs, and to store the validation errors associated with each value.

What is ModelState IsValid in C#?

ModelState. IsValid indicates if it was possible to bind the incoming values from the request to the model correctly and whether any explicitly specified validation rules were broken during the model binding process. In your example, the model that is being bound is of class type Encaissement .

What is ModelState?

The ModelState represents a collection of name and value pairs that were submitted to the server during a POST. It also contains a collection of error messages for each value submitted. Despite its name, it doesn't actually know anything about any model classes, it only has names, values, and errors.


1 Answers

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.

like image 66
Deilan Avatar answered Oct 05 '22 23:10

Deilan