Magento Custom Validation – How to Add Custom Validation to Product Options Field

form-validationjquerymagento2

I'm trying to add custom validation to the product option, I'm following the tutorial
and here it says to add custom validation element to the attribute data-validate like data-validate="{required:true, 'validate-custom-name':true}"

so far I've tried this:

require(['jquery'], function ($) {

    var rowId = $('#options_<?php /* @escapeNotVerified */ echo $rowOpId ?>_text');

    $(document).ready(function(){

        var data = $(rowId).data("validate"); // default object value

        if (!("validate-custom-name" in data)) {
            $(rowId).extend($(rowId).data("validate"), {"validate-custom-name": true});
        }
    });
});

nothing happened so far. it only shows:

<input type="text" value="" name="options[1]" data-validate="{required:true}" class="input-text product-custom-option" id="options_1_text" aria-required="true">

this is the source code of the html element, here you can see that data-validate option is not being updated.

Best Answer

Found the solution:

 require(['jquery'], function ($) {

     var rowId = $('#options_<?php /* @escapeNotVerified */ echo $rowOpId ?>_text');

     $(document).ready(function(){

         var data = $(rowId).data("validate") ; // default object value

         if (!("validate-custom-name" in data)) {
             var newObj = {"validate-custom-name": true};
             $.extend(data, newObj); //merged both in data variable
             $(rowId).attr("data-validate", JSON.stringify(data)); // set attr() as data() won't work
         }
    });
 });

Now output is as desired:

<input type="text" value="" name="options[1]" data-validate="{required:true, validate-custom-name:true}" class="input-text product-custom-option" id="options_1_text" aria-required="true">
Related Topic