How to Check if the UserName is Unique in MVC 5

In a real time web application the user registration page has a username field where the user must specify a unique username. Once a user provides a username, then to check if the field is unique, a call to the database must be made. If the field is not unique a validation error message is displayed to the front-end user such as “UserName already in use”.

Let's look at it practically.

DEMO

Step 1

The first step is to create a table where we will store the details.

  1. CREATE DATABASE db_UniqueUserName  
  2. USE db_UniqueUserName  
  1. CREATE DATABASE db_UniqueUserName  
  2. USE db_UniqueUserName  
  1. SELECT * FROM tblUser  


Step 2 

The next step is to create an MVC 5 web application.



Click OK.

Choose template as empty and select MVC as the project type.



Click OK.

Step 3

The next step is to add an ADO.Net Entity Data Model in the Models folder.



Provide this Model a name and click OK.



Choose EF Designer from database.



Click Next.

Add a new connection by clicking on the New Connection button.



Click OK.

Provide the connection settings a name.



Click Next.

Choose the required table.



Click Finish.

Step 4

Change the entity name from tblUser to User.



Step 5

The next step is to add a Controller.



Select MVC 5 Controller with views, using Entity Framework.



Click Add.

Note

This template will add all the required action methods, views and the required HTML codes for us.

Choose the Model class : User
Choose Data Context class :UserDbContext



Provide the controller a name.

Click Add

Run the application and click the Create New link.

Specify the user name and password.

Click Create.





So, a record has been added to our database.

Now add a new record and specify the same user name again and click create.

Look at the records we have. We have two records with the same user name. But in reality two users cannot have the same user name.



Now let's see how to solve this problem.

To solve this problem we can use RemoteAttribute.

Step 1

In the HomeController create a method and for that write the following.
  1. public JsonResult IsUserExists(string UserName)   
  2. {  
  3. //check if any of the UserName matches the UserName specified in the Parameter using the ANY extension method.  
  4. return Json(!db.Users.Any(x => x.UserName == UserName) ,JsonRequestBehavior.AllowGet);  
  5. }  
You might be wondering why we are returning JsonResult back. We want the validation to occur at the client side, so we are returning a JsonResult.

Step 2 

The next step is to hook this method up with the username property and for that first we need to add a class file in the models folder, add a partial User class and provide the required customization to the UserName property.
  1. using System.ComponentModel.DataAnnotations;  
  2. using System.Web.Mvc;   
  3. namespace UniqueField.Models 
  4. {  
  5.    [MetadataType(typeof(UserMetaData))]  
  6.    public partial class User 
  7.    {  
  8.    }  
  9. class UserMetaData 
  10. {  
  11.    [Remote("IsUserExists","Home",ErrorMessage="User Name already in use")]  
  12.    public string UserName { getset; }  
  13. }  
  14. }  
Step 3

In create.cshtml we need to specify the source of the three jQuery files in the given order.
  1. <h2>Create</h2>  
  2. <script src="~/Scripts/jquery-1.10.2.js"></script>  
  3. <script src="~/Scripts/jquery.validate.js"></script>  
  4. <script src="~/Scripts/jquery.validate.unobtrusive.js"></script>  
Run the application

Specify the same user name.

Without clicking the create button, we got this validation error message.



But if we specify a different username that has not been taken yet, it will not provide us the validation error message.



I hope you find this helpful.

Thank you for reading.


Similar Articles