I am working on a project where I need to validate customer registration form as customer types. I want to use the event keyup for inputs. I want to change the default messages also. Right now I am doing validation like below
$("#firstname").keyup(function(){
$('input[name="firstname"]').validation();
if(!$('input[name="firstname"]').validation('isValid')){
$("#firstname-error").remove();
$("#firstname").after('<div for="firstname" generated="true" class="mage-error" id="firstname-error">Please enter your firstname</div>');
}else{
$("#firstname-error").remove();
}
});
Not a good way of doing that I think. But I will need to do this for all fields.Then I was looking at this file vendor\magento\magento2-base\lib\web\mage\validation.js at around line no 1735 I saw below code
$.widget('mage.validation', {
options: {
meta: 'validate',
onfocusout: false,
onkeyup: false,
onclick: false,
ignoreTitle: true,
errorClass: 'mage-error',
errorElement: 'div',
...
Seeing this I thought maybe there is a better way to do this. So if there is any simple way please let me know.
After some digging, I came up with this solution. 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.app\code\Vky\Core\registration.phpapp\code\Vky\Core\etc\module.xmlapp\code\Vky\Core\view\frontend\requirejs-config.jsapp\code\Vky\Core\view\frontend\web\js\vky_custom.jsNow, wherever your
register.phtmlfile is open it. Add few things as below. At the end of the file add thisAnd then, for example, you want to validate email. Find input tag for email and add class
v-validate. Like thisSo any input with class
v-validatewill be validated on events like keyup, change, click, focusout, etc. I added a class to all input tags.For
firstnameandlastnameinregister.phtmlabove this linevar dataForm = $('#form-validate');I addedThat's all I did to solve my problem. And It works. That's why posting my answer. May be this can help someone.