0

I've tried the following code for javascript validation. When the form is submitted, only the first input field is validated. How could I validate all the dynamic values of the form?

<script type="text/javascript">
            function validate() {
                if (document.f.phone.value.length == "0") {
                    alert("Phone is required");
                    document.f.phone.focus();
                    return false;
                } else if (document.f.file.value.length == "0") {
                    alert("file is required ");
                    document.f.file.focus();
                    return false;
                } 
                
                return true;
            }   
        </script>

<?php

    echo '<form name="f" action="" method="post" enctype="multipart/form-data" onsubmit="return validate();">
           <input type="text" name="phone[]" class="required">
           <input type="file" name="file[]" class="required">
           
           <input type="button" class="add" value="add"/>
           <input type="submit" value="Submit" name="submit" class="Submit">    
    ';
    
?>
2
  • Try document.f.file.files instead of document.f.file.value. Commented Oct 10, 2020 at 20:18
  • you have defined your form elements like file[] and phone[] you need to access them like document.f.elements['phone[]'].value and document.f.elements['file[]'].value Commented Oct 10, 2020 at 21:05

1 Answer 1

1

if i understood correctly then you want to validate dynamic value in the form. instead of writing logic to validate the fields just add the required keyword to the fields which you want to make mandatory. that should save you extra effort of writing validation. go for custom validation when inbuilt validation are not enough

<form name="f" action="" method="post" enctype="multipart/form-data">
  <input type="text" name="phone[]" required class="required">
  <input type="file" name="file[]" required class="required">

  <input type="button" class="add" value="add" />
  <input type="submit" value="Submit" name="submit" class="Submit">

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.