Skip to content

Magento2: Custom validation in checkout address form

I’m trying to add a custom validation to some input fields in checkout address forms.
The official guide works fine on addressbook and other forms, extending mage/validator and using addMethod is simply and clean.

But for checkout address fields another library is used (why?!): Magento_Ui/js/lib/validation/validator which addRule lacks of many useful things. I would like to implement a rule that uses some jQuery function on the element (ie: checking the $(element).prop('disabled') status), but I can’t figure how to get the field element because every rule calls has only value and params as parameters.

I read all the code in:

    ./vendor/magento/module-ui/view/base/web/js/lib/validation/validator.js
    ./vendor/magento/module-ui/view/base/web/js/lib/validation/rules.js
    ./vendor/magento/module-ui/view/base/web/js/lib/validation/utils.js

and many docs (ie: official doc and many StackExchange threads), searching for a way to get the element where the rule is applied, but I can’t find anything useful. The only way I found is passing input[name="the_input_name"] as parameter, but it won’t work if there more than one input with the_input_name (ie: the same field name appears in shipping and payment addresses). Also seems impossible to clean up validation errors via jQuery.

After many hour of searching, trying and debugging I gave up and here I am, asking for help.
Thanks in advance 🙂