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.

asked Jun 3, 2016 at 7:20

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

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.