Mitech Preloader
Magento / Magento2

How to validate form on keyup event in Magento2

How to Validate Form on Keyup Event in Magento2

Let’s say for example you need to validate customer registration form as customer types. You want to use the events like keyup,change,focusin,focusout etc.

For the solution, all you need to do is add new js using requirejs-config.js, But I created a new module. Module files are as below.

Create app\code\Vky\Core\registration.php

[php]
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
‘Vky_Core’, __DIR__ );
[/php]

Create app\code\Vky\Core\etc\module.xml

[php]
<?xml version=”1.0″?>
<config xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xsi:noNamespaceSchemaLocation=”urn:magento:framework:Module/etc/module.xsd”>
<module name=”Vky_Core” setup_version=”0.0.1″/>
</config>
[/php]

Create app\code\Vky\Core\view\frontend\requirejs-config.js
(If you don’t want to create a new module you need to add this to your module but replace “Vky_Core” to “YourNameSpace_ModuleName”)

[php]
var config = {
map: {
‘*’: {
vky_customjs:’Vky_Core/js/vky_custom’
}
}
};
[/php]

Create app\code\Vky\Core\view\frontend\web\js\vky_custom.js
(If you don’t want to create a new module you need to add this to your module)

[php]
define([
“jquery”,
“jquery/ui”,
‘mage/validation’
], function($) {
“use strict”;
console.log(‘vky_custom.js is loaded!!’);
//creating jquery widget
$.widget(‘vky_custom.js’, {
_create: function() {
this._bind();
},

/**
* Event binding, will monitor change, keyup and paste events.
* @private
*/
_bind: function () {
this._on(this.element, {
‘change’: this.validateField,
‘keyup’: this.validateField,
‘paste’: this.validateField,
‘click’: this.validateField,
‘focusout’: this.validateField,
‘focusin’: this.validateField,
});
},

validateField: function () {
$.validator.validateSingleElement(this.element);
},

});

return $.vky_custom.js;
});
[/php]

Now, wherever your register.phtml file is open it. Add few things as below. At the end of the file add this

[php]
<script type=”text/x-magento-init”>
{ “.v-validate”: { “Vky_Core/js/vky_custom”: {} } }
</script>
[/php]

And then, for example, you want to validate Firstname. Find input tag for text and add class v-validate. Like this

[php]
<input type=”text” name=”firstname” id=”firstname” value=”<?php $block->escapeHtmlAttr($block->getFormData()->getFirstname()) ?>” title=”<?php $block->escapeHtmlAttr(__(‘FirstName’)) ?>” class=”input-text v-validate” data-validate=”{required:true}”>
[/php]

So any input with class v-validate will be validated on events like keyup, change, click, focusout, etc. I added a class to all input tags

For firstname and lastname in register.phtml above this line var dataForm = $(‘#form-validate’); I added

[php]
$(‘#firstname’).addClass(‘v-validate’);
$(‘#lastname’).addClass(‘v-validate’);
[/php]

I Hope this blog will help you.

blank