How to add new rule to rules.js?
I have created 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')
);
});
How to merge this rule to rules.js?
Best Answer
Here is a full and real working example to add a custom rule to checkout input field for checking minimum age:
Create a requirejs-config.js in your module to add a mixing to the
validator
object toNamespace/Modulename/view/frontend/requirejs-config.js
with the following content:Create a js script into your module folder into
Namespace/Modulename/view/frontend/web/js/validator-mixin.js
with the following content:USAGE
If you want to use a Magento PHP plugin to insert an input field into your checkout shipping address and validate the content of this field with the custom rule that you previously added, here is a sample code:
Create a
di.xml
file into theetc/frontend
folder of your module with the following content:Then create the
LayoutProcessor.php
file intoapp/code/Namespace/Modulename/Plugin/Block/Checkout/LayoutProcessor.php
with the following content, please update it for your needs:EDIT
Thanks @alan-storm for your explanation here https://alanstorm.com/the-curious-case-of-magento-2-mixins/ and @jisse-reitsma bring in the direction
Plus Magento 2 doc http://devdocs.magento.com/guides/v2.2/javascript-dev-guide/javascript/js_mixins.html