Search code examples
ajaxvalidationmagentounobtrusive

How to unobtrusively add new Validation methods to Magento checkout?


I want to prevent customers entering PO Boxes into the shipping address for selected Shipping Methods (UPS specifically in this case). I could override js/prototype/validation.js to insert a new validation pattern, but I don't want to fork such a key file.

Is there a mechanism to unobtrusively validate the customer's shipping address AFTER they select a shipping method via Javascript without overriding core files?

I see that Validation.add is used inside the validation.js, so it may be possible to add a new validation method outside of the core file?

The regex that I want to apply is:

\b([P|p](OST|ost)?\.?\s?[O|o|0](ffice|FFICE)?\.?\s)?([B|b][O|o|0][X|x])\s(\d+)

If the validation cannot be performed elegantly in the JS, I would be interested in an Observer on the controller_action_predispatch_onepage_saveShippingMethod that inspects the data and performs an Ajax redirect back to the shipping address form if necessary.


Solution

  • The library used is Really Easy Field Validation and that page does explain how to extend it. I guess you will need something like this:

    Validation.add('address', 'Error message text', {
        pattern : /\b([P|p](OST|ost)?\.?\s?[O|o|0](ffice|FFICE)?\.?\s)?([B|b][O|o|0][X|x])\s(\d+)/
    });