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>
asked Apr 8, 2023 at 15:40

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.

answered Apr 10, 2023 at 6:02
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 Commented Apr 10, 2023 at 10:09

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.