Validating form elements built via ui-components
Basically I was able to find the answer to this from the last comment that Marius gave.
As he said the validation for forms generated by or with the help of the ui component are validated by the /Magento/Ui/view/base/web/js/lib/validation/validator.js
'module'. Now this module has anaddRule()
function that is exactly what we need.
After adding the custom validation in the xml of your form:
<field name="title">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="dataType" xsi:type="string">text</item>
<item name="label" xsi:type="string" translate="true">Some label here</item>
<item name="formElement" xsi:type="string">input</item>
<item name="source" xsi:type="string">whatever</item>
<item name="sortOrder" xsi:type="number">999</item>
<item name="dataScope" xsi:type="string">whatever</item>
<item name="validation" xsi:type="array">
<item name="custom-validation" xsi:type="boolean">true</item>
</item>
</item>
</argument>
</field>
We must make a script that requires this 'module' and with the help of the addRule will add our custom validation:
[Namspace]/[Module]/view/[area]/web/js/our_custom_validation.js
require(
[
'Magento_Ui/js/lib/validation/validator',
'jquery',
'mage/translate'
], function(validator, $){
validator.addRule(
'custom-validation',
function (value) {
//return true or false based on your logic
}
,$.mage.__('Custom Validation message.')
);
});
Now this is not enough. We must include this file on the page that holds the form we want to validate.
We do so in the following manner: Let's say we want to add this to the customer_index_edit the [area] about will be [adminhtml] and we add the following file: [Namespace]/[Module]/view/adminhtml/layout/customer_index_edit.xml
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="admin-2columns-left" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<head>
<link src="Namespace_Module::js/our_custom_validation.js"/>
</head>
</page>
Do not forget to clean your cache deploy static content.
Hope this helps.
From what I understood
So you can add your custom validation like this:
<item name="validation" xsi:type="array">
<item name="required-entry" xsi:type="boolean">true</item>
<item name="validate-regexp" xsi:type="string">REGEXP</item>
</item>
So here REGEXP
needs to be a regular expression.
Then you will have to declare your own custom validation script to be able to handle validate-regexp
require([
'jquery', // jquery Library
'jquery/ui', // Jquery UI Library
'jquery/validate', // Jquery Validation Library
'mage/translate' // Magento text translate (Validation message translte as per language)
], function($){
$.validator.addMethod(
'validate-regexp', function (value, params) {
return value.test(params); // Validation logic here
}, $.mage.__('Enter Valid Field'));
});
NB: it may be params.test(value)
instead of value.test(params)