Magento 2 add maxlength in form ui component
-
30-01-2021 - |
Question
I know magento give max_text_length
validation for validating length & print error message regarding it, but I want to add attribute in my input field as maxlength="5"
so i can stop user to adding more value from it.
Solution
You can add below line in your:
<item name="elementTmpl" xsi:type="string">Vendor_Module/form/element/input</item>
<item name="maxlength" xsi:type="number">5</item> <!-- it's a variable which is used on template side for getting values from it-->
add VENDOR/MODULE/view/adminhtml/web/template/form/element/input.html
<input class="admin__control-text" type="text"
data-bind="
event: {change: userChanges},
value: value,
hasFocus: focused,
valueUpdate: valueUpdate,
attr: {
name: inputName,
placeholder: placeholder,
'aria-describedby': noticeId,
id: uid,
disabled: disabled,
maxlength: maxlength // here we assign dynamic value '5' from maxlength var
}"/>
after adding please run below commands:
php bin/magento setup:upgrade php bin/magento setup:static-content:deploy php bin/magento cache:flush
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange