skip to Main Content

I have a form with <input type="file">. It has display:none, so to style it I’m using a label. Every required input in the form has a "required" class. When it’s empty the form won’t be sent and there is a red border around the empty input. The problem is that when I’m trying to validate my form ("required" class is on the label since input file has display:none) and the form validation reads it like it’s always empty (no matter if I upload a file or not).

// head
<script>
        $(function () {

        $('#form').on('submit', function (e) {

            e.preventDefault();
            
            let sendForm = true;
            $('.required').each(function(){
                if ($(this).val() == ''){
                    $('#add').addClass('error');
                    $(this).addClass('error');

                    sendForm = false;
                } else {
                    $(this).removeClass('error');
                }
            })

            if (sendForm) {
                $.ajax({
                    type: "post",
                    url: 'php/php.php',
                    data: new FormData(this),
                    processData: false,
                    contentType: false,
                    success: function () {
                        document.getElementById("text").innerHTML = "success";
                        document.getElementById("add").style.border = "2px solid green";
                        $("#add").fadeOut(3000);
                    },
                    error: function () {
                        document.getElementById("text").innerHTML = "error";
                        document.getElementById("add").style.border = "2px solid red";
                    }
                });
            }

        });

        });
</script>
<form id="form" method="POST" action="php/php.php" enctype="multipart/form-data".>

<input type="text" name="Name" id="name" class="required"><br>

Image (jpg, png):
  <label for="upload_image" id="file_style" class="required">File</label>
                            
  <input type="file" style="display:none;" id="upload_image" name="Image" accept="image/*" onchange="loadFile(event)">
  <br>
  <img id="output">
                            
  <script>
    var loadFile = function(event) {
      var output = document.getElementById('output');
      output.src = URL.createObjectURL(event.target.files[0]);
      output.onload = function() {
        URL.revokeObjectURL(output.src)
      }
    };
  </script>

  <input type="number" name="Ing1" class="required">
  <input type="text" name="Ing2" class="required"><br>

  <input type="submit" name="Add" id="add">

</form>
.error{
    border: solid 12px red;
}

(This is only a minimal working example, there is more code. That’s why there are "useless" functions.)
How can I make it so if the file is uploaded the validation script doesn’t see it as undefined?

2

Answers


  1. Chosen as BEST ANSWER

    I think I found the solution. I added this code:

    $('.required2').each(function(){
      if ($(this).val() == ''){
        $('#file_style').addClass('error');
        sendForm = false;
      } else {
        $('#file_style').removeClass('error');
      }
    })
    

    into my submit function. I will need to change a few things to suit my needs, but it works as it should. Thank you all for the help and ideas how to fix it!


  2. First, you don’t have a function called "loadFile", I’m not sure if you need it.

    Second, in the $('.required').each, you loop throw labels, you need to get the input that associated with that label, so one solution is to get it by id after getting for attribute of the label, then check if there are files in the input file, by input.files.length.

    .error{
        border: solid 12px red;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <head>
    <script>
            $(function () {
    
            $('#form').on('submit', function (e) {
    
                e.preventDefault();
                
                let sendForm = true;
                $('.required').each(function(index, label){
                    const input = document.getElementById(label.getAttribute('for'))
                    if (!input.files.length){
                        $('#add').addClass('error');
                        $(this).addClass('error');
    
                        sendForm = false;
                    } else {
                        $(this).removeClass('error');
                        $('#add').removeClass('error');
                    }
                })
    
                if (sendForm) {
                    $.ajax({
                        type: "post",
                        url: 'php/php.php',
                        data: new FormData(this),
                        processData: false,
                        contentType: false,
                        success: function () {
                            document.getElementById("text").innerHTML = "success";
                            document.getElementById("add").style.border = "2px solid green";
                            $("#add").fadeOut(3000);
                        },
                        error: function () {
                            document.getElementById("text").innerHTML = "error";
                            document.getElementById("add").style.border = "2px solid red";
                        }
                    });
                }
    
            });
    
            });
    </script>
    </head>
    
    
    <body>
    <form id="form" method="POST" action="php/php.php" enctype="multipart/form-data".>
    Image (jpg, png):
      <label for="upload_image" id="file_style" class="required">File</label>
                                
      <input type="file" style="display:none;" id="upload_image" name="Image" accept="image/*">
      <br>
    
      <input type="submit" name="Add" id="add">
      
      <div id="text"></div>
    
    </form>
    </body>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search