Last updated on October 18, 2023

WP Forms front-end validation

Don’t know where to add this snippet? Read our guide: How to add code snippets.

Validate forms on the front-end with WP Forms.

The code snippet provided below demonstrates how to perform front-end validation for WP Forms using JavaScript. This is useful when you want to validate user input before submitting the form to the server.

jQuery(document).ready(function($) {
  // Add custom validation rules
  $.validator.addMethod('custom_rule', function(value, element) {
    // Add your custom validation logic here
    return this.optional(element) || /* validation condition */;
  }, 'Please enter a valid value.');

  // Initialize form validation
  $('#my-form').validate({
    rules: {
      field_name: {
        required: true,
        custom_rule: true
      }
    },
    messages: {
      field_name: {
        required: 'This field is required.',
        custom_rule: 'Please enter a valid value.'
      }
    },
    submitHandler: function(form) {
      // Handle form submission
      form.submit();
    }
  });
});

To use this code snippet, you need to replace 'my-form' with the ID of your WP Form. Additionally, you can add custom validation rules by extending the $.validator.addMethod function. Inside the validation method, you can define your own validation logic and return true or false based on the validation result.

The rules object specifies the validation rules for each form field. In this example, we have a field with the name 'field_name' that is required and should pass the custom validation rule 'custom_rule'.

The messages object defines the error messages to be displayed for each validation rule. You can customize these messages to fit your requirements.

Finally, the submitHandler function is called when the form is successfully validated. You can add your own logic here, such as submitting the form via AJAX or redirecting to a different page.

Overall, this code snippet allows you to add front-end validation to WP Forms, ensuring that user input meets your specified criteria before submitting the form.

Examples

Example 1: Custom front-end validation for WP Forms

This example demonstrates how to implement custom front-end validation for WP Forms using JavaScript. The code snippet below shows how to add a custom validation rule to check if a phone number is valid.

(function($) {
    $(document).on('wpformsValidateField', function(e, field, form) {
        if (field.attr('name') === 'phone') {
            var phone = field.val();
            var regex = /^d{10}$/;
            if (!regex.test(phone)) {
                field.addClass('wpforms-error');
                field.after('<div class="wpforms-error-message">Please enter a valid phone number.</div>');
                e.preventDefault();
            }
        }
    });
})(jQuery);

Explanation: This code adds an event listener to the wpformsValidateField event, which is triggered when a form field is validated. It checks if the field with the name “phone” fails the custom validation rule (in this case, a 10-digit phone number). If the validation fails, it adds the wpforms-error class to the field and displays an error message.

Example 2: Custom front-end validation for multiple fields

This example demonstrates how to implement custom front-end validation for multiple fields in WP Forms. The code snippet below shows how to add custom validation rules for email and password fields.

(function($) {
    $(document).on('wpformsValidateField', function(e, field, form) {
        if (field.attr('name') === 'email') {
            var email = field.val();
            var regex = /^[^s@]+@[^s@]+.[^s@]+$/;
            if (!regex.test(email)) {
                field.addClass('wpforms-error');
                field.after('<div class="wpforms-error-message">Please enter a valid email address.</div>');
                e.preventDefault();
            }
        }
        if (field.attr('name') === 'password') {
            var password = field.val();
            if (password.length < 8) {
                field.addClass('wpforms-error');
                field.after('<div class="wpforms-error-message">Password must be at least 8 characters long.</div>');
                e.preventDefault();
            }
        }
    });
})(jQuery);

Explanation: This code adds an event listener to the wpformsValidateField event and checks if the field with the name “email” fails the email validation rule or if the field with the name “password” fails the password length validation rule. If any of the validations fail, it adds the wpforms-error class to the field and displays an error message.

Example 3: Custom front-end validation with server-side check

This example demonstrates how to implement custom front-end validation with a server-side check in WP Forms. The code snippet below shows how to add a custom validation rule to check if a username is already taken.

(function($) {
    $(document).on('wpformsValidateField', function(e, field, form) {
        if (field.attr('name') === 'username') {
            var username = field.val();
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'wpsnippets_check_username',
                    username: username
                },
                success: function(response) {
                    if (response === 'taken') {
                        field.addClass('wpforms-error');
                        field.after('<div class="wpforms-error-message">Username is already taken.</div>');
                        e.preventDefault();
                    }
                }
            });
        }
    });
})(jQuery);

Explanation: This code adds an event listener to the wpformsValidateField event and checks if the field with the name “username” fails the server-side validation rule. It sends an AJAX request to the server, passing the username as data. If the server responds with “taken”, it adds the wpforms-error class to the field and displays an error message.

Last updated on October 18, 2023. Originally posted on December 27, 2023.

Leave a Reply

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