I'm trying to modify some validation rules for the State input in shipping address. I want to add an error message if user selects 'Texas'.
I created a mixin for Magento_Ui/js/lib/validation/rules
in requirejs-config.js
I can add a new rule called 'customTexasValidationRule' in the rules collection. However i don't know how to apply this rule to the select input.
I see that i can declare the rules in the select template at vendor/magento/module-ui/view/frontend/web/templates/form/element/select.html
but i don't want to create a new template file for such a small task.
Is there any quick and easy way to add such a small custom validation in Magento 2?
Best Answer
I have figured out a way to accomplish this:
I added a mixin for
Magento_Ui/js/lib/validation/validator
:Then i added this to
etc/frontend/di.xml
, depending the modules you installed, you may have differentLayoutProcessorProvider
, or you may have to useMagento\Checkout\Block\Checkout\LayoutProcessor
, see the link i mention at the bottom for more details, here i have a checkout module to modify my checkout flow calledMyVendor\MyCheckoutModule
so i have this:Then i added this
Validation.php
fileClear caches and refresh, the validation is now working with my select input in the billing address form.
Note that the structure could be different in
$jsLayout
, as i'm having a module to modify the checkout process so my structure is not the same with stock magento 2 layout.Big thanks to Add rule to rules.js Magento2 for leading me in the right direction