DEV Community 👩‍💻👨‍💻

Techsolutionstuff
Techsolutionstuff

Posted on • Originally published at techsolutionstuff.com

How To Validate Upload File Type Using Javascript

Today we will see how to validate upload file type using javascript. here, we easily check the selected file extension with allowed file extensions and we can restrict the user to upload only the allowed file types using file upload validation in jquery.

laravel provide in built file type validation in controller but it works server side only it means we can received validation message after form submit, here i will give you example to check file type before submit data in form using javascript.Currently we have checking only specific file extention like ".txt" , ".csv" etc... or you can use all file types like "image/* ".

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>File upload type validation in javascript - techsolutionstuff.com</title>
  <link href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet">
  <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>  
</head>
<body>
  <h3 style="text-align: center;">File upload type validation in javascript - techsolutionstuff.com</h3>
  <div class="col-md-6 col-md-offset-5"><br>
  <input type="file" name="file"  id="filesizecheck"><br>
  <span id="error-message" class="validation-error-label"></span>
  </div>
</body>
</html>
<script type="text/javascript">
  $(document).ready(function(){
    $('#filesizecheck').on('change',function(){
      myfiles = $(this).val();
      var ext = myfiles.split('.').pop();
      if(ext == "txt" || ext == "png"){
        $('#error-message').css("display","none");
      }else{
        $('#error-message').html("Only allow valid file inputs.");
        $('#error-message').css("display","block");
        $('#error-message').css("color","red");
      }
    });
  });
</script>
Enter fullscreen mode Exit fullscreen mode

And you will get output like below image.

How To Validate Upload File Type Using Javascript


You might also like :

Read Also : How To Validate Max File Size Using Javascript

Read Also : How To Integrate Paypal Payment Gateway In Laravel 8

Read Also : How To Create Dynamic Pie Chart In Laravel

Top comments (0)

This post blew up on DEV in 2020:

js visualized

🚀⚙️ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! 🥳

Happy coding!