There doesn't appear to be "proper Magento" way to do this (it would be nice if this message was configurable in the Admin area!), but I figured out one way to get this working with Swatches for Size and Color with a Theme file override.
Magento 2 form validation is built on the jQuery Validation plugin, which is actually pretty easy to set custom validation messages with, but it can be more difficult depending on which Magento component you are working with.
To change the validation messages for Configurable product "Swatch" attributes, I had to override the JS file that dynamically builds the Swatch elements:
vendor/magento/module-swatches/view/frontend/web/js/swatch-renderer.js
into my theme:
app/design/frontend/YourCompany/yourtheme/Magento_Swatches/web/js/swatch-renderer.js
Then I modified the _RenderFormInput()
method which outputs the swatch <input>
elements to have the data-msg-required
attribute, like so:
_RenderFormInput: function (config) {
var msgTxt = $.mage.__("Please select");
return '<input class="' + this.options.classes.attributeInput + ' super-attribute-select" ' +
'name="super_attribute[' + config.id + ']" ' +
'type="text" ' +
'value="" ' +
'data-selector="super_attribute[' + config.id + ']" ' +
'data-validate="{required:true}" ' +
// THIS IS WHAT I ADDED
'data-msg-required="' + msgTxt + ' ' + config.label + '" ' +
'aria-required="true" ' +
'aria-invalid="true" ' +
'style="visibility: hidden; position:absolute; left:-1000px">';
},
config.label
is the human readable, translated attribute name.
The jQuery Validation plugin parses this and uses it as the validation error message. The required
part of the data-msg-required
attribute name reflects the required
validator. If the minlength
rule were being used, the data-msg-minlength
attribute would customize that error message, etc. (Docs)
If you look up how to customize the validation messages for the jQuery Validation plugin you'll find other methods as well:
https://stackoverflow.com/questions/6777634/jquery-validation-plugin-custom-message