Magento – Make required field to Gift Option in Magento 2

fieldsetsformsmagento2required

I enable gift option from magento 2 admin. Now i want to make required. field on cart page.

I found that template is coming from vendor/magento/module-gift-message/view/frontend/web/template/gift-message-form.html

I know how we override html files but don't know how we make require filed in html form of magento 2.

<div class="field field-from">
    <label for="gift-message-whole-from" class="label">
        <span data-bind="i18n: 'From:'"></span>
    </label>
    <div class="control">
        <input type="text"
               id="gift-message-whole-from"
               class="input-text"
               data-bind="value: getObservable('sender')">
    </div>
</div>

I used this but not luck

method #1 – by setting data-validate attribute on the input field:

<input data-validate='{"required":true}'name="field1" id="field1" ... />

method #2 – by setting the rule names as attributes:

<input required="true" name="field2" id="field2" ... />

method #3 – by setting the rule names as classnames:

<input class="input-text required" name="field3" id="field3" ... />

Best Answer

Override this template and add required="true" inside <input>. So that in your case:

<div class="field field-from">
    <label for="gift-message-whole-from" class="label">
        <span data-bind="i18n: 'From:'"></span>
    </label>
    <div class="control">
        <input type="text"
               id="gift-message-whole-from"
               class="input-text"
               data-bind="value: getObservable('sender')"
               required="true">
    </div>
</div>

Step 1 is not required in your case as the validation is loaded within the form already when the website run vendor/magento/module-gift-message/view/frontend/templates/inline.phtml

Ref: http://inchoo.net/magento-2/validate-custom-form-in-magento-2/