Read More
Read More
Menu Close

    Add custom validation rule in UI component form field

    Hello Dear Friends!!!

    In this article, we are going to learn how we can add custom validation in a field in UI component form.
    First of all, we will create our custom validation js file. Here, I have created wk-storeurl-validation.js file inside the <magento-root-dir>/app/code/Vendor/Module/view/adminhtml/web/js/ directory.

    ], function(validator, $){
                function (value) {
                    return !(/[^a-z^A-Z^0-9\.\-]/g.test(value));
                $.mage.__('Store Url can contain dash (-) and alphanumric values only.')

    Now, we will add this file to the head section of the layout file. Here, I have added my js file in routename_customform_edit.xml file inside the <magento-root-dir>/app/code/Vendor/Module/view/adminhtml/layout/ directory.

    <?xml version="1.0"?>
    <page xmlns:xsi="" layout="admin-2columns-left"  xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
        <update handle="styles"/>
            <link src="Vendor_Module::js/wk-storeurl-validation.js"/>
            <referenceContainer name="content">
                <uiComponent name="tenants_form"/>

    Now, we will add our custom validation rule in the form field in the UI component form. Here, I have added my custom validation rule named “wk-storeurl-validation” in the store_url field in the tenants_form.xml file as follows:

    <field name="store_url">
                <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">Store URL</item>
                        <item name="formElement" xsi:type="string">input</item>
                        <item name="dataScope" xsi:type="string">store_url</item>
                        <item name="required" xsi:type="boolean">true</item>
                        <item name="notice" xsi:type="string" translate="true">
                           Enter store URL name. For example: xyzshop
                        <item name="validation" xsi:type="array">
                            <item name="required-entry" xsi:type="boolean">true</item>
                            <strong><item name="wk-storeurl-validation" xsi:type="boolean">true</item></strong>
                            <item name="validate-no-html-tags" xsi:type="boolean">true</item>

    Now, when we input the wrong value in the form field store_url and save the form, then we will get an error as in the following image:


    Hope this will be helpful.
    Thanks 🙂

    Searching for an experienced
    Magento 2 Company ?
    Read More
    . . .
    Discuss on Helpdesk

    Leave a Comment

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

    Be the first to comment.

    Back to Top