2

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.

1 Answer 1

2

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">
1
  • I can only after 2 days according to the policy.
    – R T
    Commented Jun 3, 2016 at 9:12

Your Answer

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

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