Magento – Magento 2 : Validate form fields that are loaded with Knockout on blur-event

form-validationformsjavascriptknockoutjsmagento2

I have a form that is generated through a .phtml file, and in this form various fields are loaded with KnockOut (using the uiComponent javascript-object).

.phtml:

<form action="#" class="form checkout__account" method="post" data-mage-init='{"validation":{}}'>
    <?php echo $block->getBlockHtml('formkey'); ?>
    <fieldset class="fieldset" data-bind="scope:'vendor_module_account'">
        <!--
            Account form:
        -->
        <!-- ko template: getTemplate() --><!-- /ko -->
    </fieldset>
</form>

.html (which is inserted in ko template: getTemplate()):

<input type="text" name="login[username]" id="email" class="input-text required-entry"
       data-validate="{required:true, 'validate-email':true}"
       data-bind="event:{change:checkEmailAddress,blur:checkEmailAddress,keypress:absorbEnter},value:emailAddress" />

Now I can get it why this wouldn't directly work on blur, but also when I submit the form (Using the inspector $0.submit()) the validation doesn't get executed.

Another interesting detail: the form gets an attribute novalidate="novalidate" added, I guess by the data-mage-init-attribute.

Anyone know why my form isn't validated and/or what I have to do is make it validate on submit/blur?

Best Answer

Well, 4 years from this question but I found a solution for those facing this issue as I was today.

In your js component file, import this:

...
'jquery/validate',
'mage/validation'
...

And then we must override the original validate function, at least I had to:

/** @inheritdoc */
  validate: function () {
  const $form = $('#your-form')
  $form.validation()
  return $form.valid()
},

Finally, associate the validate to the click bind on the form element:

<form 
        method="post" 
        id="your-form" 
        class="form form-default" 
        data-bind="click: validate"
>

That's it. It works fine and you can now manipulate the validate function and use it's result to call or not other functions. When the validation fails, it returns false.

Hope it helps.