【发布时间】:2023-04-07 16:23:01
【问题描述】:
我需要在可使用的所有地方对国家/地区字段添加验证。
对于注册或地址编辑,它工作正常,但在结帐时我尝试了几种方法,但没有任何效果。我想在新的送货地址表单的字段上进行验证。
- 我将验证添加到 js 文件
countryValidation.js中:
用于注册或编辑地址的相同脚本,它工作正常
define([
'jquery',
'jquery/ui',
'mage/validation',
'mage/translate',
'domReady!'
], function($){
'use strict';
return function(validator) {
$.validator.addMethod(
"validate-country",
function(value, element) {
if (value === "FR") {
var zipValue = $('input[name="postcode"]').val();
if (zipValue) {
return !(zipValue.startsWith("97") || zipValue.startsWith("98"));
}
}
return true;
},
$.mage.__("You cannot choose France for DOM-TOM Zip Code")
);
return validator;
}
});
- 我在模块的
requirejs-config.js中注册了它:
var config = {
config: {
mixins: {
'Magento_Ui/js/lib/validation/validator': {
'Gone_Customer/js/countryValidation': true
}
}
}
};
- 为了向结帐方法添加验证,我尝试了不同的方法
-> 方法 A : 使用插件
class AddCountryValidation
{
public function afterProcess(
\Magento\Checkout\Block\Checkout\LayoutProcessor $subject,
array $jsLayout
) {
// Country ID
$jsLayout['components']['checkout']['children']['steps']['children']['shipping-step']['children']['shippingAddress']['children']['shipping-address-fieldset']['children']['country_id']['validation']['validate-country'] = true;
return $jsLayout;
}
}
-> 方法 B:在属性中添加验证规则
在customer_eav_attribute 属性country_id 中为validate_rules 添加{"validate-country": true}
当我验证表单时,我应该有一个验证错误。
如果我遗漏了什么,你能告诉我吗?
【问题讨论】:
标签: validation magento2 checkout