0

I would like to use jQuery to validate two fields on NEW/EDIT page of a Wordpress website in a way that When either of both fields are empty and Publish button is pressed, there is a warning:

  1. Please enter a post title (Post Title field)
  2. Please enter a price (Price field) (Please note that I dont want to use default warning saying that "Please fill out this field" initiated by HTML itself)

I have tried the following jQuery codes, but they dont work.

Very appreciate any advice of working codes.

    // HTML:
    <input type="text" name="post_title" size="30" value="" id="title">
    <input type="text" name="price" size="30" value="" id="price">


    // jQuery:
    jQuery('#title').prop('required',true);
    var loops = document.getElementsByTagName("post_title");
    for (var i = 0; i < loops.length; i++) {
      loops[i].oninvalid = function(e) {
          e.target.setCustomValidity("");
          if (!e.target.validity.valid) {
              e.target.setCustomValidity("Please enter a post title");
          }
      };
      elements[i].oninput = function(e) {
          e.target.setCustomValidity("");
      };
    }


    jQuery('#price').prop('required',true);
    var elements = document.getElementsByTagName("price");
    for (var i = 0; i < elements.length; i++) {
      elements[i].oninvalid = function(e) {
          e.target.setCustomValidity("");
          if (!e.target.validity.valid) {
              e.target.setCustomValidity("Please enter a price");
          }
      };
      elements[i].oninput = function(e) {
          e.target.setCustomValidity("");
      };
    }
2
  • 1
    Are you using the classic editor or the block editor? Jan 24 at 5:40
  • Yes, I use classic editor. Thanks
    – daro2013
    Jan 24 at 5:57

2 Answers 2

1

I fixed the issues by replacing default HTML warning message using function setCustomValidity(). The default HTML warning message is issued at invalid field so that users know where to correct:

      // HTML:
      <input type="text" name="post_title" size="30" value="" id="title">
      <input type="text" name="price" size="30" value="" id="price">

      // jQuery:
      // Make post title field required - when it is blank, a default warning is issued
      jQuery('#title').prop('required', true);    
      
      // Change default HTML warning message when title field is blank
      let title = document.getElementById("title");
      title.addEventListener("input", function(e){
        title.setCustomValidity('');
      });
      title.addEventListener("invalid", function(e){
        title.setCustomValidity('Please enter your post title'); //custom validation message for invalid text
      });
      
      // Make price field required - when it is blank, a default warning is issued
      jQuery('#price').prop('required', true);    
      
      // Change default HTML warning message when price field is blank
      let price = document.getElementById("price");
      price.addEventListener("input", function(e){
        price.setCustomValidity('');
      });
      price.addEventListener("invalid", function(e){
        price.setCustomValidity('Please enter a price'); //custom validation message for invalid text
      });

Many thanks

0

The code snippet you provided can be optimized for better performance and clarity. The issues in your current code include incorrect use of getElementsByTagName (which should be getElementById or a similar function, since you are targeting specific elements by their IDs) and some redundancies in setting custom validation messages.

Here's a revised version of your jQuery code that should work for your requirements:

jQuery(document).ready(function($) {

    $('#publish').click(function(e){
        var isValid = true;

        // Validate Post Title
        var postTitle = $('#title').val().trim();
        if (postTitle === '') {
            alert('Please enter a post title');
            isValid = false;
        }

        // Validate Price
        var price = $('#price').val().trim();
        if (price === '') {
            alert('Please enter a price');
            isValid = false;
        }

        // If either field is empty, prevent form submission
        if (!isValid) {
            e.preventDefault();
        }
    });

});

Form Submission Trigger: The code listens for a click on the "Publish" button (assuming its ID is publish). If your publish button has a different ID, you need to adjust the selector $('#publish') accordingly.

Validation Check: It checks if the "Post Title" and "Price" fields are empty. If either is empty, it displays an alert and sets isValid to false.

Prevent Form Submission: If any field is invalid (isValid is false), it prevents the form from being submitted (e.preventDefault()).

This approach uses simple conditional checks and alerts for validation messages. It's straightforward and integrates seamlessly with your existing WordPress setup. Remember to enqueue this script correctly in your WordPress theme or plugin using the guidelines you provided (function wpb_enqueue_scripts_plugin_name).

2
  • WordPress Buddha, Many thanks. I ll test your codes, and will give a feedback soon
    – daro2013
    Jan 25 at 8:16
  • WordPress Buddha, Your codes work perfectly as intended. However, the warning popup windows displays a TICK box asking users "Dont allow www.mywebsite.com to prompt you again" when trying to press Publish button seond time as below: Please enter a price Don't allow www.mywebsite.com to prompt you again. or: Please enter a post title Don't allow www.mywebsite.com to prompt you again. If users tick it, there wont be more warnings in the future posts if those fields are blank. is it possible to disable that Tick box in the warning popup windows?
    – daro2013
    Jan 25 at 12:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.