In this tutorial, we will explore how to implement both client-side and server-side form validation using jQuery and WordPress functions. By combining jQuery’s validation plugin with WordPress’ backend checks, we can ensure data integrity and improve user experience. Below is a detailed guide to create and validate form fields such as username, email, password, and confirm password.
Step 1: Load jQuery and Validation Plugin
Ensure that jQuery and the jQuery Form Validator are included in your project:
<!-- 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 Your Form
Set up a simple HTML form for validation:
<form id="registrationForm"> <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">Register</button> </form>
Step 3: Apply Validation Rules
Utilize the validate() method to apply rules for form fields:
<script>
$(document).ready(function() {
$("#registrationForm").validate({
rules: {
username: {
required: true,
pattern: /^[A-Za-z_]+$/,
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"
}
}
});
});
</script>
Step 4: Add Custom Validation
For advanced validation, such as preventing numeric values in usernames, we can use the addMethod function from jQuery:
<script>
$.validator.addMethod("noNumeric", function(value, element) {
return this.optional(element) || /^[^0-9]+$/i.test(value);
}, "No numeric values allowed.");
</script>
Step 5: Server-Side Checks in WordPress
Add WordPress hooks for checking username and email existence:
// Check if username exists
add_action('wp_ajax_check_username_exists', 'check_username_exists');
function check_username_exists() {
$username = $_POST['username'];
echo username_exists($username) ? 'false' : 'true';
exit;
}
This combination of client-side and server-side validation ensures that form data is properly validated both before and after submission, securing your forms against errors and malicious input.
