Magento2: custom validation Error “Uncaught TypeError: Cannot read property 'call' of undefined”
-
15-04-2021 - |
Question
In my custom validation rules shows '
Uncaught TypeError: Cannot read property 'call' of undefined' errors!!!...
. how can i do custom logic and proper validation ?
Here is my Code
app/code/{vendor}/{module}/view/frontend/web/template/form/element/email.html
<input class="input-text"
type="text"
data-bind="
textInput: email,
hasFocus: emailFocused,
mageInit: {'mage/trim-input':{}}"
name="username"
data-validate="{required:true,'validate-custom-key':true}"
id="customer-email" />
app/code/{vendor}/{module}/view/frontend/requirejs-config.js
// JavaScript Document
var config = {
map: {
'*': {
script: 'Vendor_Module/js/script'
},
'*': {
'Vendor_Module/js/action/login': 'Vendor_Module/js/action/login'
},
'*': {
'Magento_Checkout/template/form/element/email.html':
'Vendor_Module/template/form/element/email.html'
}
}, mixins: {
'Magento_Ui/js/lib/validation/validator': {
'Vendor_Module/js/validator-mixin': true
}
}
};
app/design/frontend/Smartwave/porto/web/js/validator-mixin.js
define([
'jquery'
], function ($) {
"use strict";
return function () {
$.validator.addMethod(
'validate-custom-key',
function (value) {
// Some custom validation stuff here
return false;
},
$.mage.__('Your validation error message')
);
}
});
jquery.validate.js:556 Uncaught TypeError: Cannot read property 'call of undefined
No correct solution
OTHER TIPS
Try the following way:
use addRule instead of addMethod.
define([
'jquery',
'jquery/validate'
], function ($) {
"use strict";
return function (validator) {
validator.addRule(
'validate-custom-key',
function (value) {
// Some custom validation stuff here
return false;
},
$.mage.__('Your validation error message')
);
return validator;
};
});
If you want to attach validator using data-validate
on input element, you have to:
- This js file content seems to be alright.
- In requirejs config add it like this:
var config = {
map: {
'Vendor_Module/js/validator': true // removed "mixin" from file name as it is not a mixin anymore
}
}
- In HTML somewhere after input element you need to add something like this:
<script type="text/x-magento-init">
{
"*": {
"Vendor_Module/js/validator": {}
}
}
</script>
This way jquery attaches this validator and will be able to use it. You can read more about attaching validator this way here: https://aureatelabs.com/magento-2/add-custom-validation-rule-in-magento-2/ (I'm not the author of this article, I just used it to solve the same problem you encountered).
If you want to use mixin, then you might need to attach this validator using PHP or XML.