Skip to content
the poor coder

jQuery Validate remote method usage to check if username already exists

Poor Man
Published
Reading time
4 min read
On this page

Using jQuery Validate remote method to check if username already exists#

If you're building a web application that requires users to create an account, one of the common validations you'll need to perform is checking if a username already exists in your database. For this, you can use the remote method provided by jQuery Validate plugin.

Step 1: Include jQuery and jQuery Validate plugin#

Make sure you have included jQuery and jQuery Validate plugin in your HTML file before using it. You can download the plugin from the official website or use a CDN link.

Text

<!-- jQuery CDN link -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<!-- jQuery Validate plugin CDN link -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.3/jquery.validate.min.js"></script>

Step 2: Add a validation rule for the username field#

Create a form with the username field and add a validation rule to it using the remote method. The remote method sends an AJAX request to the server to check if the username already exists in the database.

Text

<form id="signup-form">
  <label for="username">Username:</label>
  <input type="text" id="username" name="username">
  <span id="username-error"></span>
  <br>
  <button type="submit">Submit</button>
</form>

<script type="text/javascript">
  $(document).ready(function() {
    $("#signup-form").validate({
      rules: {
        username: {
          required: true,
          remote: {
            url: "check_username.php",
            type: "post",
            data: {
              username: function() {
                return $("#username").val();
              }
            }
          }
        }
      },
      messages: {
        username: {
          required: "Please enter a username.",
          remote: "Username already exists. Please choose a different one."
        }
      },
      errorElement: "span",
      errorPlacement: function(error, element) {
        error.appendTo("#" + element.attr("id") + "-error");
      }
    });
  });
</script>

In the validation rules, we have added the remote method for username field with the URL of a PHP file that will check if the username already exists and returns true or false. The type of request is POST since we are sending data to the server. We have also passed the username value as data to the server.

In the messages object, we have added a message for the remote validation rule which will be displayed if the server returns false.

The errorElement and errorPlacement options are used to specify the error message container and its placement in the HTML.

Step 3: Create a PHP file to check if username already exists#

Create a PHP file (check_username.php) that checks if the username already exists in your database and returns true or false as a response. The response needs to be in JSON format.

Text

<?php
  $username = $_POST['username'];
  
  // check if username already exists in database
  // return true or false as JSON response
  $response = array(
    'valid' => true // or false
  );
  
  header('Content-Type: application/json');
  echo json_encode($response);
  exit;
?>

You can modify the code according to your database structure and query to check if the username already exists.

Alternative way: Using custom remote method#

Instead of using the built-in remote method, you can create a custom remote method that checks if the username already exists in your database using AJAX. This gives you more control over the validation logic.

Text

$.validator.addMethod("checkUsername", function(value, element) {
  var response = false;
  $.ajax({
    url: "check_username.php",
    type: "post",
    data: {
      username: value
    },
    async: false,
    success: function(data) {
      response = data.valid;
    }
  });
  return response;
}, "Username already exists. Please choose a different one.");

$("#signup-form").validate({
  rules: {
    username: {
      required: true,
      checkUsername: true
    }
  },
  messages: {
    username: {
      required: "Please enter a username.",
      checkUsername: "Username already exists. Please choose a different one."
    }
  },
  // ...
});

Here, we have added a custom remote validation method named checkUsername which sends an AJAX request to the server to check if the username already exists in the database. The response is stored in a variable which is returned by the method.

In the validation rules, we have used the checkUsername method for the username field.

In the messages object, we have added a message for the checkUsername validation rule which will be displayed if the server returns false.

Both methods achieve the same result, so choose whichever method suits your needs.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC