将规则添加到rules.js Magento2


10

如何将新规则添加到rules.js?我创建了extra-rules.js

define(
[
    'jquery',
    'Magento_Ui/js/lib/validation/validator'
], function ($, validator) {
    "use strict";
    return validator.addRule('phoneNO',
        function (value) {
            return value.length > 9 && value.match(/^(\(?(0|\+44)[1-9]{1}\d{1,4}?\)?\s?\d{3,4}\s?\d{3,4})$/);
        },
        $.mage.__('Please specify a valid phone number')
    );
});

如何将此规则合并到rules.js?

Answers:


21

这是一个完整而实际的工作示例,用于向结帐输入字段添加自定义规则以检查最小年龄:

在模块中创建一个requirejs-config.js,以向validator对象添加Namespace/Modulename/view/frontend/requirejs-config.js以下内容的混合:

var config = {
    config: {
        mixins: {
            'Magento_Ui/js/lib/validation/validator': {
                'Namespace_Modulename/js/validator-mixin': true
            }
        }
    }
};

Namespace/Modulename/view/frontend/web/js/validator-mixin.js包含以下内容的模块文件夹中创建一个js脚本:

define([
    'jquery',
    'moment'
], function ($, moment) {
    'use strict';

    return function (validator) {

        validator.addRule(
            'validate-minimum-age',
            function (value, params, additionalParams) {
                return $.mage.isEmptyNoTrim(value) || moment(value, additionalParams.dateFormat).isBefore(moment().subtract(params.minimum_age, 'y'));
            },
            $.mage.__("Sorry, you don't have the age to purchase the current articles.")
        );

        return validator;
    };
});

用法

如果要使用Magento PHP插件将输入字段插入到结帐收货地址,并使用之前添加的自定义规则来验证此字段的内容,请参见以下示例代码:

使用以下内容在模块di.xmletc/frontend文件夹中创建一个文件:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">    
    <type name="Magento\Checkout\Block\Checkout\LayoutProcessor">
        <plugin name="CheckoutLayoutProcessor" type="Namespace\Modulename\Plugin\Block\Checkout\LayoutProcessor" />
    </type>
</config>

然后使用以下内容创建LayoutProcessor.php文件app/code/Namespace/Modulename/Plugin/Block/Checkout/LayoutProcessor.php,请根据需要进行更新:

<?php
/**
 * diglin GmbH - Switzerland
 *
 * @author      Sylvain Rayé <support **at** diglin.com>
 * @category    diglin
 * @package     diglin
 * @copyright   Copyright (c) diglin (http://www.diglin.com)
 */

namespace MyNamespace\Modulename\Plugin\Block\Checkout;

use MyNamespace\Modulename\Helper\AgeValidation;

/**
 * Class LayoutProcessor
 * @package MyNamespace\Modulename\Plugin\Block\Checkout
 */
class LayoutProcessor
{
    /**
     * @var \MyNamespace\Checkout\Helper\AgeValidation
     */
    private $ageValidation;
    /**
     * @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface
     */
    private $timezone;
    /**
     * @var \Magento\Framework\App\Config\ScopeConfigInterface
     */
    private $scopeConfig;

    /**
     * LayoutProcessor constructor.
     *
     * @param \MyNamespace\Checkout\Helper\AgeValidation $ageValidation
     * @param \Magento\Framework\Stdlib\DateTime\TimezoneInterface $timezone
     * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
     */
    public function __construct(
        AgeValidation $ageValidation,
        \Magento\Framework\Stdlib\DateTime\TimezoneInterface $timezone,
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
    )
    {
        $this->ageValidation = $ageValidation;
        $this->timezone = $timezone;
        $this->scopeConfig = $scopeConfig;
    }

    /**
     * Checkout LayoutProcessor after process plugin.
     *
     * @param \Magento\Checkout\Block\Checkout\LayoutProcessor $processor
     * @param array $jsLayout
     *
     * @return array
     */
    public function afterProcess(\Magento\Checkout\Block\Checkout\LayoutProcessor $processor, $jsLayout)
    {
        $shippingConfiguration = &$jsLayout['components']['checkout']['children']['steps']['children']['shipping-step']
        ['children']['shippingAddress']['children']['shipping-address-fieldset']['children'];

        // Checks if shipping step available.
        if (isset($shippingConfiguration)) {
            $shippingConfiguration = $this->processAddress(
                $shippingConfiguration
            );
        }

        return $jsLayout;
    }

    /**
     * Process provided address to contains checkbox and have trackable address fields.
     *
     * @param $addressFieldset - Address fieldset config.
     *
     * @return array
     */
    private function processAddress($addressFieldset)
    {
        $minimumAge = $this->ageValidation->getMinimumAge();
        if ($minimumAge === null) {
            unset($addressFieldset['my_dob']);
        } else {
            $addressFieldset['my_dob'] = array_merge(
                $addressFieldset['my_dob'],
                [
                    'component' => 'Magento_Ui/js/form/element/date',
                    'config' => array_merge(
                        $addressFieldset['my_dob']['config'],
                        [
                            'elementTmpl' => 'ui/form/element/date',
                            // options of datepicker - see http://api.jqueryui.com/datepicker/
                            'options' => [
                                'dateFormat' => $this->timezone->getDateFormatWithLongYear(),
                                'yearRange' => '-120y:c+nn',
                                'maxDate' => '-1d',
                                'changeMonth' => 'true',
                                'changeYear' => 'true',
                                'showOn' => 'both',
                                'firstDay' => $this->getFirstDay(),
                            ],
                        ]
                    ),
                    'validation' => array_merge($addressFieldset['my_dob']['validation'],
                        [
                            'required-entry' => true,
                            'validate-date' => true,
                            'validate-minimum-age' => $minimumAge, // custom value in year - array('minimum_age' => 16)
                        ]
                    ),
                ]
            );
        }

        return $addressFieldset;
    }

    /**
     * Return first day of the week
     *
     * @return int
     */
    public function getFirstDay()
    {
        return (int)$this->scopeConfig->getValue(
            'general/locale/firstday',
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        );
    }
}

编辑

感谢@ alan-storm在这里的解释https://alanstorm.com/the-curious-case-of-magento-2-mixins/和@ jisse-reitsma带来了方向

加上Magento 2文档http://devdocs.magento.com/guides/v2.2/javascript-dev-guide/javascript/js_mixins.html


1
我得到一个错误Loading failed for the <script> with source “.../validator-mixin.js"Script error for: Namespace_Modulename/js/validator-mixin
Jurģis汤姆斯Liepiņš

1
validator-mixin.js位置应该是:/view/frontend/web/js/validator-mixin.js
Jurģis汤姆斯Liepiņš

1
不起作用,Magento 2只是忽略了这一点
cjohansson

@cjohansson可能是因为它是针对Magento 2.1和2.2项目完成的。如果使用2.3,则可能不再可行。就我们而言,它适用于我提到的版本
SylvainRayé19年



0

它为我工作:

在模块中创建一个requirejs-config.js,以向验证器对象添加混合到app / design / frontend / Vendor / Theme / Magento_Ui / requirejs-config.js,其内容如下:

var config = {
    config: {
        mixins: {
            'Magento_Ui/js/lib/validation/rules': {
                'Magento_Ui/js/lib/validation/rules-mixin': true
            }
        }
    }
};

在您的模块文件夹中的app / design / frontend / Vendor / Theme / Magento_Ui / web / js / lib / validation / rules-mixin.js中创建一个js脚本,其内容如下:

define([
    'jquery',
    'underscore',
    'moment',
    'mage/translate'
], function ($, _, moment) {
    'use strict';

    return function (validator) {
        var validators = {
            'letters-spaces-only': [
                function (value) {
                    return /^[a-zA-Z ]*$/i.test(value);
                },
                $.mage.__('Only letters and spaces.')
            ]
        };

        validators = _.mapObject(validators, function (data) {
            return {
                handler: data[0],
                message: data[1]
            };
        });

        return $.extend(validator, validators);
    };
});
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.