经过一番挖掘,我想出了这个解决方案。对于解决方案,您需要做的就是使用requirejs-config.js
. 但我创建了一个新模块。模块文件如下。
app\code\Vky\Core\registration.php
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Vky_Core',
__DIR__
);
app\code\Vky\Core\etc\module.xml
<?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>
app\code\Vky\Core\view\frontend\requirejs-config.js
var config = {
map: {
'*': {
vky_customjs: 'Vky_Core/js/vky_custom'
}
}
};
app\code\Vky\Core\view\frontend\web\js\vky_custom.js
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;
});
现在,无论您的register.phtml
文件在哪里打开它。如下添加一些东西。在文件末尾添加这个
<script type="text/x-magento-init">
{ ".v-validate": { "Vky_Core/js/vky_custom": {} } }
</script>
然后,例如,您要验证电子邮件。查找电子邮件的输入标签并添加类v-validate
。像这样
<input type="email" name="email" autocomplete="email" id="email_address" value="<?= $block->escapeHtmlAttr($block->getFormData()->getEmail()) ?>" title="<?= $block->escapeHtmlAttr(__('Email')) ?>" class="input-text v-validate" data-validate="{required:true, 'validate-email':true}">
因此,任何带有类的输入v-validate
都将在 keyup、change、click、focusout 等事件上得到验证。我为所有输入标签添加了一个类。
在这条线的上方,firstname
我lastname
添加了register.phtml
var dataForm = $('#form-validate');
$('#firstname').addClass('v-validate');
$('#lastname').addClass('v-validate');
这就是我为解决我的问题所做的一切。它有效。这就是为什么发布我的答案。可能这可以帮助某人。