0

I have a unit length that accept entering cm, inch and ft. I know how to set-up the input validation in one limit. Let say, I want to have max limit to 100cm. I can set the field validation to the following:

<input name="length" type="text" data-validate="{required:true, max:100}" />

And let say, I have a select field that contain the unit of length:

<select name="unit">
    <option value="cm">cm</option>
    <option value="inch">inch</option>
    <option value="ft">ft</option>
</select>

The problem is: If I enter 100ft or 100inch, the validation still pass. How can I adjust the max value when I switch the unit? So that 100ft or 100inch cannot pass the validation.

1 Answer 1

0

Finally it's just the matter of JS. First of all, modify the select list a bit:

<select name="unit">
    <option value="cm" data-conversion="0.03280840">cm</option>
    <option value="inch"data-conversion="0.08333333">inch</option>
    <option value="ft" data-conversion="1.00000000">ft</option>
</select>

Then, write the following JS. You can load it right under the select list, or via requirejs:

<script type="text/javascript">
    require([
        'jquery',
        'mage/mage'
    ], function($){
        //Change the value depends on the size unit        
        $("select[name='unit']").change(function () {
            var selected = $(this).find('option:selected');
            curr_price = selected.data("conversion");
            curr_max = $('input[name="length]"').rules("max");
            cm_price = $('option[value=cm]').data("price");
            new_max_range = curr_max * cm_price / curr_price;
            $('input[name="length]"').rules("remove", "max");
            $('input[name="productoptions[<?php echo $option->getOptionCode() ?>]"').rules("add", {
                    max: new_max_range
            });
        });
    });
</script>

I just solved it long time ago, but forgot to answer it till now.

2
  • Which File ?? I Will Chnage attribute value inch to semi . Commented Feb 25, 2019 at 6:28
  • I forgot the exact file. Just remember on category product page
    – PY Yick
    Commented Feb 26, 2019 at 1:21

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.