Magento 2 – Fix data-mage-init Validation Not Working with Knockout Component

form-validationknockoutjsmagento2

I have a phtml file with a form that used data-mage-init

<form data-mage-init='{"validation": {}}' class="form" id="custom-form" method="post" autocomplete="off">
</form>

and then I initialize a knockout component at the bottom of the page

<script type="text/x-magento-init">
    {
        "#custom-form": {
            "Magento_Ui/js/core/app": {
               "components": {
                    "mycomponent": {
                        "component": "Company_Module/js/mycomponent"
                    }
                }
            }
        }
    }
</script>

For some reason the validation only works when I remove the "x-magento-init" script at the bottom. I had to make the validation work by calling click using knockoutjs on the button and validating in the component
When the "x-magento-init" script is on the page, the submit call on the validation never seems to happen. I can't figure out why? Anyone know?

Best Answer

If you want to use validation in UI component you need to use data-bind="mageInit: {'validation': {}}" instead of data-mage-init='{"validation":{}}'.

So you form tag should looks like this:

<form data-bind="mageInit: {'validation': {}}" class="form" id="custom-form" method="post" autocomplete="off"> </form>