0

Simplify tthe code especially. Probem: only the first elemts will be validated on submit field-2 will be validated if I'll remove first field. Strange problem. Not depends of M2 vesion. That's phtml inclided to the CMS page

<form action="#" method="post" id="testform_01" class="testform">

    <div class="form-row">
        <label for="field-1">Text</label>
        <input type="text" id="field-1" data-validate='{"required":true}'/>
    </div>

    <div class="form-row">
        <label for="field-2">Text</label>
        <input type="text" id="field-2" data-validate='{"required":true}'/>
    </div>

    <div class="buttons">
        <button class="form-submit">Submit</button>
    </div>

</form>

<script type="text/x-magento-init">
    {
        "#testform_01": {
            "validation": {}
        }
    }
</script>

1 Answer 1

1

You can simplify your code by removing the data-validate attribute from your input fields and instead using a validation rule in your script. Here's an example:

   <form action="#" method="post" id="testform_01" class="testform">

        <div class="form-row">
            <label for="field-1">Text</label>
            <input type="text" id="field-1"/>
        </div>

        <div class="form-row">
            <label for="field-2">Text</label>
            <input type="text" id="field-2"/>
        </div>

        <div class="buttons">
            <button class="form-submit">Submit</button>
        </div>

    </form>

    <script type="text/x-magento-init">
        {
            "#testform_01": {
                "validation": {
                    "rules": {
                        "field-1": {
                            "required": true
                        },
                        "field-2": {
                            "required": true
                        }
                    }
                }
            }
        }
    </script>

In this example, the validation rules for each input field are specified in the "rules" object within the "validation" object. This ensures that both fields will be validated on form submission, regardless of whether one of the fields has been removed.

Also note that you can use the id attribute of the input fields to specify the validation rules for each field.

1
  • Yes, sure, the fine way. BTW, the problem of my code example was that this was a draft and I didn't use name attributies
    – Max.A
    Apr 10, 2023 at 10:09

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.