Magento2 : Custom Validation

Inside ui_component write below code in ui_component xml
<settings>
 <validation>
     <rule name="custom-validation" xsi:type="boolean">true</rule>
 </validation>
</settings>
Inside layout write below code in layout xml file
<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">
    <update handle="styles"/>
    <head>
        <link src="Namespace_Modulue::js/custom-validation.js"/>
    </head>
</page>

Inside web-> js create a new file custom-validation.js and write code
require(
    [  'jquery',
        'Magento_Ui/js/lib/validation/validator',
        'Magento_Ui/js/lib/validation/utils',
        'uiRegistry',
        'uiComponent',
        'underscore'
    ],function ($,validator,utils,uiRegistry,Component,_) {
    "use strict";
    return validator.addRule('custom-validation',function (value) {
       
         return !utils.isEmpty(value);
        
    }, $.mage.__('This is a required field.'));
});

Comments

Post a Comment