Custom Validation
Category

How to add custom validation to Magento 2 admin form field

It happens sometimes that you need to add some custom validation to your admin form field, and doing this is not very tricky, you just need to follow the mentioned steps and you can easily able to achieve that.

Step 1: Define your custom validation handle in your form ui-component like this.

<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">Your Label</item>
            <item name="formElement" xsi:type="string">input</item>
            <item name="source" xsi:type="string">source</item>
            <item name="sortOrder" xsi:type="number">14</item>
            <item name="dataScope" xsi:type="string">scope</item>
            <item name="validation" xsi:type="array">
                <item name="custom-validation" xsi:type="boolean">true</item>
            </item>
        </item>
    </argument>
</field>

Step 2: You need to put your validation code in a js file and keep that file at this location.

[Namspace]/[Module]/view/adminhtml/web/js/your_custom_validation_file.js

Step 3: Third and last step is to write your custom validation code in the above-defined file in the way mentioned below.

require(
[
'Magento_Ui/js/lib/validation/validator',
'jquery',
'mage/translate'
], function(validator, $) {
validator.addRule( 'custom-validation', function (value) {
// your custom validation code will go here
// and then return true or false based on your code logic
},
$.mage.__('Custom Validation message.')
);
});

Happy Coding 🫶

Leave a Reply

Your email address will not be published. Required fields are marked *