Jquery Form Validator With User Name Exist User Email Exist

To implement jQuery Form Validator with the specified validation rules, including required, minlength, email, equalTo, custom validation, confirm password, username pattern, email existence in the database in WordPress, and username with no numeric value, you’ll need to combine client-side validation using jQuery Form Validator with server-side validation using PHP and WordPress functions. Here’s a step-by-step guide:

Step 1: Include jQuery and jQuery Form Validator
Make sure you have jQuery and the jQuery Form Validator plugin loaded in your HTML document. Include them in the <head> section of your HTML:

 

<!-- 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: Create Your Form
Create an HTML form with input fields that you want to validate:

<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: Apply Validation Rules
Use the `validate()` method provided by the jQuery Form Validator to apply validation rules to your form. Specify the rules for each input field using the `rules` option and define error messages using the `messages` option.

<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
If you want to add custom validation, use the `addMethod` function provided by jQuery Validator. For example, let’s create a custom validation rule for a field named “noNumeric” that should not contain any numeric values:

<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 Validation in WordPress
To check if the username and email exist in the database, as well as the username with no numeric value, handle the AJAX requests on the server-side using WordPress actions and functions. Add the following PHP code to your theme’s `functions.php` file or a custom plugin:

 

// 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;
}

The above PHP code creates three AJAX actions: `check_username_exists`, `check_email_exists`, and `check_username_no_numeric`. The first two actions check if the username and email exist in the WordPress database using `username_exists()` and `email_exists()` functions, respectively. The third action uses a regular expression to check if the username contains any numeric values.

Step 6: Server-Side AJAX URL
In the client-side validation code, you’ll notice the `url: ajaxurl` property for the `remote` rule. This property is set to the global `ajaxurl` variable that WordPress provides for AJAX requests. However, to make this work, you need to enqueue your script and localize the AJAX URL in your theme’s `functions.php` file or a custom plugin. Add the following code:

 

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'));
}

 

Replace `get_stylesheet_directory_uri() . ‘/js/custom-script.js’` with the correct path to your custom JavaScript file. This code enqueues the custom JavaScript file and uses `wp_localize_script` to pass the AJAX URL to the script.

That’s it! Your form should now be validated with the specified rules, including server-side validation in WordPress for email and username existence checks. The username field should also be validated to ensure it contains no numeric values. Customize the rules, error messages, and patterns to suit your specific form requirements. Always test your form thoroughly to ensure both client-side and server-side validation are working correctly. Client-side validation provides a better user experience, while server-side validation ensures data integrity and security.

Categories
Scroll to Top

Request A Quote