Skip to content

Custom Error Messages for Product Add-Ons

Recently I ran across a request to update the required field tooltips in Product Add-Ons. These little messages are actually just generic ones created by the browser. If you only want to replace the text, we can use a bit of JavaScript to find the inputs and then add a custom oninvalid attribute to each one.

First we set a variable to represent all of the inputs we want to modify. In this example, I’m using a checkbox group. If you need to use a different class, inspect the input on the front end of your website with your developer tools and then update the classname.

const inputsToUpdate = document.querySelectorAll( '[class="wc-pao-addon-checkbox-group-required"] input' );

Next we set the message that we’d like to use. In this snippet, you only want to replace the Your custom message text and leave the rest as is.

const valMessage = "this.setCustomValidity( 'Your custom message.')";

Next up, we need to loop through these inputs and add the attribute to each one. When we put it all together, it’ll look something like this.

const inputsToUpdate = document.querySelectorAll( '[class="wc-pao-addon-checkbox-group-required"] input' );
const valMessage = "this.setCustomValidity( 'Your custom message.')";
const updateInputs = ( inputs ) => {
   inputs.forEach(( element ) => {
      element.setAttribute( "oninvalid", valMessage );
   });
};
updateInputs( inputsToUpdate );

Now on the front end of the site, if I try to add this product to the cart without selecting an add-on, my custom error message will be displayed.

If you have any questions, please add them in the comments.

Leave a Reply

%d bloggers like this: