jQuery Validator for Form with Email and Username Check

Want to validate your form inputs in WordPress using jQuery Form Validator along with checks for existing email and username? This guide walks you through integrating client-side and server-side validation, ensuring your data is secure and accurate.

Step 1: Include Required Libraries

<!-- jQuery library --> 
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> 
<!-- jQuery Form Validator --> 
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>

 

Step 2: Build the HTML Form

<form id="myForm">
  <label for="username">Username:</label>
  <input type="text" name="username" id="username" required pattern="[A-Za-z0-9_]+">

  <label for="email">Email:</label>
  <input type="email" name="email" id="email" required>

  <label for="password">Password:</label>
  <input type="password" name="password" id="password" required minlength="6">

  <label for="confirmPassword">Confirm Password:</label>
  <input type="password" name="confirmPassword" id="confirmPassword" required equalTo="#password">

  <button type="submit">Submit</button>
</form>

 

Step 3: Add Validation Logic

<script>
  $(document).ready(function() {
    $("#myForm").validate({
      rules: {
        username: {
          required: true,
          pattern: /^[A-Za-z_]+$/, // Only letters and underscores allowed
          remote: {
            url: ajaxurl,
            type: "post",
            data: {
              action: "check_username_exists",
              username: function() {
                return $("#username").val();
              }
            }
          }
        },
        email: {
          required: true,
          email: true,
          remote: {
            url: ajaxurl,
            type: "post",
            data: {
              action: "check_email_exists",
              email: function() {
                return $("#email").val();
              }
            }
          }
        },
        password: {
          required: true,
          minlength: 6
        },
        confirmPassword: {
          required: true,
          equalTo: "#password"
        }
      },
      messages: {
        username: {
          required: "Please enter a username.",
          pattern: "Only letters and underscores are allowed.",
          remote: "This username is already taken."
        },
        email: {
          required: "Please enter your email address.",
          email: "Please enter a valid email address.",
          remote: "This email address already exists."
        },
        password: {
          required: "Please enter a password.",
          minlength: "Password must be at least 6 characters long."
        },
        confirmPassword: {
          required: "Please confirm your password.",
          equalTo: "Passwords do not match."
        }
      }
    });
  });
</script>

 

Step 4: Add Custom Validation (No Numbers)

<script>
  $(document).ready(function() {
    $.validator.addMethod(
      "noNumeric",
      function(value, element) {
        return this.optional(element) || /^[^0-9]+$/i.test(value);
      },
      "Please enter a value without numeric characters."
    );

    $("#myForm").validate({
      rules: {
        // Other rules here
        noNumericField: {
          noNumeric: true
        }
      },
      messages: {
        // Other messages here
        noNumericField: {
          noNumeric: "Please enter a value without numeric characters."
        }
      }
    });
  });
</script>

 

Step 5: Server-Side Checks (WordPress)

// Check if username exists in the database
add_action('wp_ajax_check_username_exists', 'check_username_exists');
add_action('wp_ajax_nopriv_check_username_exists', 'check_username_exists');

function check_username_exists() {
    $username = $_POST['username'];
    $user_id = username_exists($username);

    if ($user_id) {
        echo 'false';
    } else {
        echo 'true';
    }
    exit;
}

// Check if email exists in the database
add_action('wp_ajax_check_email_exists', 'check_email_exists');
add_action('wp_ajax_nopriv_check_email_exists', 'check_email_exists');

function check_email_exists() {
    $email = $_POST['email'];
    $user_id = email_exists($email);

    if ($user_id) {
        echo 'false';
    } else {
        echo 'true';
    }
    exit;
}

// Check if username contains no numeric value
add_action('wp_ajax_check_username_no_numeric', 'check_username_no_numeric');
add_action('wp_ajax_nopriv_check_username_no_numeric', 'check_username_no_numeric');

function check_username_no_numeric() {
    $username = $_POST['username'];

    if (preg_match('/\d/', $username)) {
        echo 'false';
    } else {
        echo 'true';
    }
    exit;
}

 

Step 6: Localize AJAX URL

add_action('wp_enqueue_scripts', 'my_enqueue_scripts');

function my_enqueue_scripts() {
    wp_enqueue_script('my-custom-script', get_stylesheet_directory_uri() . '/js/custom-script.js', array('jquery', 'jquery-validate'), '1.0', true);
    wp_localize_script('my-custom-script', 'ajaxurl', admin_url('admin-ajax.php'));
}

 

This setup ensures both client- and server-side checks, creating a strong validation mechanism in WordPress.

Leave a Comment

Your email address will not be published. Required fields are marked *

Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.