DEV Community


How To Validate Upload File Type Using Javascript

websolutionstuff profile image Websolutionstuff Originally published at ・2 min read

Hello Guys,

In this post I will teach you how to validate upload file type using javascript. Using this post we can easily check the selected file extension with allowed file extensions and we can restrict the user to upload only the allowed file types.

laravel also provide file type validation in controller but it is 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/* ".

In this example i will check file type using on change event and get the value of input type file. After that we will get extension using split() and pop () function.

Then we will check if else condition. if both are same then nothing to display error message otherwise display error message using javascript.

So, copy below code and get output as we discussed.

<!DOCTYPE html>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>File upload type validation in javascript -</title>
  <link href="" rel="stylesheet">
  <script src=""></script>  
  <h3 style="text-align: center;">File upload type validation in javascript -</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>
<script type="text/javascript">
      myfiles = $(this).val();
      var ext = myfiles.split('.').pop();
      if(ext == "txt" || ext == "png"){
        $('#error-message').html("Only allow valid file inputs.");
Enter fullscreen mode Exit fullscreen mode

And you will get output like below image.

how to validate upload file type using javascript

Read Also : How To Validate Max File Size Using JavaScript

Discussion (0)

Editor guide