3

I am trying to give required field validation on textbox which is depend on dropdown selected value.

Dropdown have 2 values 1. Yes 2.No.

If dropdown selected value is Yes than textbox is mandatory else not.

This thing i want in Admin grid edit form in magento 2.

Any help will appreciated.

Thanks in advance

1 Answer 1

1

Try this way:

Add JS component to your text field.

ui_component/UiForm.xml

<item name="component" xsi:type="string">Namespace_Modulename/js/form/element/text</item>

Write logic in your JS

app/code/Namespace/Modulename/view/adminhtml/web/js/form/element/text.js

define([
    'jquery',
    'underscore',
    'uiRegistry',
    'Magento_Ui/js/form/element/text',      
    'Magento_Ui/js/modal/modal'
], function ($,_, uiRegistry, text, modal) {
    'use strict';
    return select.extend({      

        initialize: function (){
            this.addValidation();
        },
        addValidation: function(){
            selectValue = $('input[name="labelconfig[select_field]"]').val();
            if(selectValue == 'yes') {
                $('input[name="labelconfig[text_field]"]').addClass("add magento validation class name");
            }
        }, 
    });
});

I hope it helps!

6
  • i know this will work but i don't know what logic i have to apply in js function. can you please tell me? May 29, 2019 at 7:01
  • I have updated answer using $('input[name="labelconfig[select_field]"]').val(); i will get value of select field and based on value you can add magento validation class using jquery. May 29, 2019 at 7:16
  • Above code is not tested you have to check and update code. May 29, 2019 at 7:17
  • If you can't get input field value then include JS using require config May 29, 2019 at 7:18
  • Thanks for giving me your valuable time, i will test it and let you know does it work or not. May 29, 2019 at 7:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.