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에 병합하는 방법?

답변:


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
        );
    }
}

편집하다

여기에 대한 설명은 앨런 폭풍 @ 덕분에 https://alanstorm.com/the-curious-case-of-magento-2-mixins/ 와 @ jisse - reitsma는 방향으로 가져

Plus 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 Toms Liepiņš

1
validator-mixin.js위치 :/view/frontend/web/js/validator-mixin.js
Jurģ is Toms Liepiņš

1
하지 작업, 젠토 2 단지이 무시합니까
cjohansson

@cjohansson은 아마도 Magento 2.1 및 2.2 프로젝트에서 수행 되었기 때문일 것입니다. 2.3을 사용하면 더 이상 가능하지 않을 수 있습니다. 우리의 경우 그것은 내가 언급 한 버전 일
실뱅 Rayé

1

원본 rules.js은 모든 규칙을 포함하는 객체 리터럴을 반환합니다. 이 파일에 믹스 인을 추가하여이 객체 리터럴을 수정할 수 있습니다. Magento 문서는이를 수행하는 방법에 대한 지침을 제공합니다. Magento Javascript Mixins



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);
    };
});
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.